将 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 时遇到任何问题,请随时通过 免费产品支持论坛 联系我们。

相关链接

我们建议您访问以下链接以了解更多信息