將 html 轉換為 pdf

如何將 HTML 轉換為 PDF |線上 HTML 轉 PDF

HTML 是 Web 開發的領先文件格式,大多數現代 Web 瀏覽器都支援 HTML 規格。儘管它獨立於平台並且可以在任何作業系統上查看,但它們也容易受到惡意腳本的影響,並且無法輕鬆透過網路共享。因此,為了避免這種情況以及長期存檔,我們將網頁另存為PDF(便攜式文件格式)。因此,在本文中,我們將討論如何使用 Java REST API 將 HTML 轉換為 PDF 的步驟。

HTML 到 PDF 轉換 API

Aspose.HTML Cloud SDK for Java 可讓您在 Java 應用程式中執行 HTML 操作操作。我們也可以將 HTML 轉換為固定版面配置文件格式(PDF 或 XPS)。因此,為了執行轉換,我們可以從雲端儲存載入來源 HTML(XHTMLMHTMLEPUBMarkdown)或提供一個網頁的 URL。現在為了使用 SDK,請在 maven 建置專案的 pom.xml 中新增以下相依項,以便將 aspose-html.jar 加入到專案中:

<repositories> 
    <repository>
        <id>aspose-cloud</id>
        <name>artifact.aspose-cloud-releases</name>
        <url>http://artifact.aspose.cloud/repo</url>
    </repository>   
</repositories>

<dependencies>
    <dependency>
        <groupId>com.aspose</groupId>
	<artifactId>aspose-html-cloud</artifactId>
	<version>20.7.0</version>
	<scope>compile</scope>
    </dependency>
</dependencies>

在 Java 中將 HTML 轉換為 PDF

請依照以下步驟在 Java 應用程式中將網頁轉換為 PDF。

  • 首先,我們需要根據 Configuration.setAPPSID 指定詳細資訊。
  • 其次,我們指定Configuration.setAPIKEY資訊。
  • 第三,我們設定 setBasePath(..) 詳細資料。
  • 然後我們需要指定 setAuthPath(..) 詳細資料。
  • 將 setUserAgent(…) 設定為 WebKit。
  • 為了我們自己的幫助,我們將 setDebug(..) 設為 true。
  • API 還允許我們指定結果檔案的邊距詳細資訊。
  • 下一步是讀取輸入 HTML 檔案並將其載入到 File 實例中。
  • 現在我們需要建立 RequestBody 類別的實例並將媒體解析為「multipart/form-data」。
  • 建立 ConversionApi 類別的物件。
  • 由於我們要將檔案上傳到雲端存儲,所以我們還需要建立一個StorageApi的實例。
  • 現在我們需要呼叫 PostConvertDocumentInRequestToPdf(..) 來啟動轉換過程。此方法接受輸入檔案名稱、結果檔案名稱以及結果檔案邊距和尺寸詳細資訊作為參數。
  • 轉換後,結果將返回包含回應正文的原始位元組的 Stream 物件。
  • 現在我們需要將成功回應的反序列化回應正文檢索到 ResponseBody 物件中。
  • 將產生的檔案從雲端儲存下載到 ResponseBody 物件。
  • 最後,我們將呼叫自訂方法將產生的 PDF 文件保存在本機系統磁碟機上。
import com.aspose.html.api.ConversionApi;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Call;
import java.io.*;
public class conversionCode {
    public static void main(String[] args) {
    com.aspose.html.Configuration.setAPP_SID("c235e685-1aab-4cda-a95b-54afd63eb87f");
    com.aspose.html.Configuration.setAPI_KEY("b8da4ee37494f2ef8da3c727f3a0acb9");
    com.aspose.html.Configuration.setBasePath("https://api.aspose.cloud/v3.0");
    com.aspose.html.Configuration.setAuthPath("https://api.aspose.cloud/connect/token");
    com.aspose.html.Configuration.setUserAgent("WebKit");
    com.aspose.html.Configuration.setDebug(true);
		
    String name = "Simple.html";// inpit Document name.
		    	
    Integer width = 800; // Resulting image width.
    Integer height = 1000; // Resulting image height.
    Integer leftMargin = 10; // Left resulting image margin.
    Integer rightMargin = 10; // Right resulting image margin.
    Integer topMargin = 10; // Top resulting image margin.
    Integer bottomMargin = 10; // Bottom resulting image margin.
    String storage = null; // Name of the storage.
    File f = new File("/Users/nayyershahbaz/Documents/"+name);
    if(!f.exists()){
	System.out.println("file not found");
	}
    RequestBody requestBody = RequestBody.create( MediaType.parse("multipart/form-data"), f);
    MultipartBody.Part file = MultipartBody.Part.createFormData("file", f.getName(), requestBody);
				
    try {			
	ConversionApi api = new com.aspose.html.ApiClient().createService(ConversionApi.class);
	com.aspose.html.api.StorageApi storageApi = new com.aspose.html.ApiClient().createService(com.aspose.html.api.StorageApi.class);
		        
        Call<ResponseBody> call2 = api.PostConvertDocumentInRequestToPdf("resultantFile.pdf", file, width, height, leftMargin, rightMargin, topMargin, bottomMargin);
	retrofit2.Response<ResponseBody> res = call2.execute();
	ResponseBody resultant = res.body();
      	call2 = storageApi.downloadFile("resultantFile.pdf", null, storage);
      	checkAndSave(call2, "resultantFile.pdf");
        } catch (Exception e) {
	System.err.println("Exception during file processing...");
	e.printStackTrace();
	}
    } // main ends here
	
public static void checkAndSave(Call<ResponseBody> call, String fileName) throws IOException 
{
    retrofit2.Response<ResponseBody> res = call.execute();
    ResponseBody answer = res.body();
    //儲存到測試目錄
    boolean result = saveToDisc(answer, fileName);
}
  
public static boolean saveToDisc(ResponseBody body, String fileName) 
{
    File savedFile = new File("/Users/nayyershahbaz/Documents/"+fileName);
    try (InputStream inputStream = body.byteStream();
    OutputStream outputStream = new FileOutputStream(savedFile))
    {
    	byte[] fileReader = new byte[4096];
	long fileSizeDownloaded = 0;

	while (true) {
	int read = inputStream.read(fileReader);
	if (read == -1) break;

	outputStream.write(fileReader, 0, read);
	fileSizeDownloaded += read;
	}
	outputStream.flush();
	return true;

    } catch (Exception e) {
	e.printStackTrace();
	return false;
    }
} // saveToDisc ends here

}

結論

在本文中,我們學習如何使用 Java SDK 將網頁轉換為 PDF 的步驟。我們觀察到,用更少的程式碼行,完整的 HTML 就可以完全保真地呈現為 PDF 格式。除了 PDF 格式外,此 API 還允許您執行 HTML 到 JPG、HTML 到 PNG、HTML 到 TIFF、HTML 到 BMP 和 HTML到 GIF 的轉換操作。同樣,我們可以使用相同的 API 將 Markdown 檔案轉換為 HTML 或將 MHTML 轉換為 HTML 格式。

如果您在使用 API 時遇到任何問題,請隨時透過免費產品支援論壇與我們聯絡。

相關連結

我們建議訪問以下連結以了解更多信息