微调转换器 – 在 Java 中转换 HTML、MHTML、EPUB 和 SVG
使用 Aspose.HTML for Java,您可以通过几种方法将 HTML 转换为各种流行格式:
- 使用
Converter类的 convertHTML() 方法。这是将 HTML 转换成各种格式的最常用方法。 - 通过使用
HTMLDocument类的 renderTo(device) 方法或 Renderer 类的render()方法。这种渲染 HTML 文档的替代方法可让您在 Java 应用程序中更轻松地控制 HTML 渲染过程。
渲染设备
渲染(输出)设备封装了一个二维绘图表面,其 API 使用 IDevice 接口实现。目前,Aspose.HTML for Java API 实现了一组渲染设备– PdfDevice、 XpsDevice、 DocDevice 和 ImageDevice,分别用于生成 PDF、XPS、DOCX 和 Image 文件格式。
下一个示例展示了如何使用 PdfDevice,将 HTML 文档渲染为 PDF 文件。该过程使用默认的渲染选项:
- 加载 HTML 文档。
- 使用 PdfDevice() 构造函数之一创建一个 PdfDevice 类实例。
- 调用
HTMLDocument类的 renderTo(device) 方法。
1// Render HTML to PDF using Java
2
3// Prepare HTML code
4String code = "<span>Hello, World!!</span>";
5
6// Initialize an HTML document from HTML code
7HTMLDocument document = new HTMLDocument(code, ".");
8
9// Create an instance of the PdfDevice class and specify the output file to render
10PdfDevice device = new PdfDevice("output.pdf");
11
12// Render HTML to PDF
13document.renderTo(device);渲染选项
渲染选项为你提供了对输出设备的额外控制。每个渲染设备 PdfDevice、 XpsDevice 和 ImageDevice 都有自己独特的选项集,并分别通过类 PdfRenderingOptions、 XpsRenderingOptions、 DocRenderingOptions 和 ImageRenderingOptions 来实现。例如,你可以改变页面大小,调整页边距和背景颜色,通过调整图像质量和分辨率来减小文件大小,如果使用 PdfDevice,还可以设置安全密码等。
下面演示了如何使用 PdfRenderingOptions 在 HTML 到 PDF 的渲染过程中自定义页面大小:
1// Render HTML to PDF in Java with custom page size
2
3// Prepare HTML code
4String code = "<span>Hello, World!!</span>";
5
6// Initialize a HTML document from the HTML code
7HTMLDocument document = new HTMLDocument(code, ".");
8
9// Create an instance of PdfRenderingOptions and set a custom page-size
10PdfRenderingOptions options = new PdfRenderingOptions();
11PageSetup pageSetup = new PageSetup();
12Page anyPage = new Page();
13anyPage.setSize(
14 new Size(
15 Length.fromInches(5),
16 Length.fromInches(2)
17 )
18);
19pageSetup.setAnyPage(anyPage);
20options.setPageSetup(pageSetup);
21
22// Create a PDF Device and specify options and output file
23PdfDevice device = new PdfDevice(options, "output.pdf");
24
25// Render HTML to PDF
26document.renderTo(device);一般选项
渲染选项为您提供了对输出设备的额外控制。com.aspose.html.rendering 包由许多呈现器对象和相应的底层选项类组成,负责将文档呈现到 IDevice 实现中。RenderingOptions 和 CssOptions 类代表渲染选项,或者换句话说,一般的渲染选项。
常规选项适用于从 HTML 到 PDF、XPS、DOCX 和图像的所有渲染设备和所有渲染过程。让我们来看看其中的一些选项:
水平和垂直分辨率
水平和垂直分辨率设置对于将 HTML 呈现为其他格式(例如 HTML 到 PDF)时实现高质量输出至关重要。水平和垂直分辨率以每英寸像素(dpi)为单位进行测量(获取和设置),默认值为 300 dpi。此设置可确保 PDF 中的文本、图像、水平线和垂直线等元素细节清晰、渲染流畅。
下面的示例展示了如何控制生成 PDF 文件的分辨率,最终影响其大小和质量:
1// Render HTML to PDF with custom resolution using Java
2
3// Prepare HTML code and save it to a file
4String code = "< style >\n" +
5 " p\n" +
6 " {\n" +
7 " background:\n" +
8 " blue;\n" +
9 " }\n" +
10 " @media(min - resolution:300dpi)\n" +
11 " {\n" +
12 " p\n" +
13 " {\n" +
14 " /* high resolution screen color */\n" +
15 " background:\n" +
16 " green\n" +
17 " }\n" +
18 " }\n" +
19 " </style >\n" +
20 " <p > Hello World !! </p >\n";
21
22try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.html")) {
23 fileWriter.write(code);
24}
25
26// Create an instance of the HTMLDocument class
27HTMLDocument document = new HTMLDocument("document.html");
28
29// Create options for low-resolution screens
30PdfRenderingOptions options = new PdfRenderingOptions();
31options.setHorizontalResolution(Resolution.to_Resolution(50d));
32options.setVerticalResolution(Resolution.to_Resolution(50d));
33
34// Create an instance of the PdfDevice
35PdfDevice device = new PdfDevice(options, "output_resolution_50.pdf");
36
37// Render HTML to PDF
38document.renderTo(device);
39
40// Create options for high-resolution screens
41options = new PdfRenderingOptions();
42options.setHorizontalResolution(Resolution.to_Resolution(300d));
43options.setVerticalResolution(Resolution.to_Resolution(300d));
44
45// Create an instance of PDF device
46device = new PdfDevice(options, "output_resolution_300.pdf");
47
48// Render HTML to PDF
49document.renderTo(device);CSS 媒体类型
CSS 媒体类型是一项重要功能,它规定了文档在不同媒体上的呈现方式:屏幕、纸张、盲文设备等。通过链接样式表或内联样式表为样式表指定媒体类型的方法不多:
链接样式表
1<link rel="stylesheet" type="text/css" media="print" href="style.javas">内联样式表
1<style type="text/css">
2@media print {
3 body{ color: #000000; }
4}
5</style>Aspose.HTML for Java 支持这一功能,因此您可以通过应用相应的媒体类型和样式表,将 HTML 文档转换成屏幕上或印刷品上的样子。下面的示例展示了如何设置媒体类型:
1// Render HTML to PDF with custom MediaType settings with Java
2
3// Prepare HTML code
4String code = "<span>Hello, World!!</span>";
5
6// Initialize an HTML document from the HTML code
7HTMLDocument document = new HTMLDocument(code, ".");
8
9// Create an instance of the PdfRenderingOptions class
10PdfRenderingOptions options = new PdfRenderingOptions();
11// Set the 'screen' media-type
12options.getCss().setMediaType(MediaType.Screen);
13
14// Create a PDF Device and specify options and output file
15PdfDevice device = new PdfDevice(options, "output.pdf");
16
17// Render HTML to PDF
18document.renderTo(device);请注意, CssOptions.MediaType 的默认值是 Print(打印)。这意味着文档将应用与打印设备相关的样式表进行转换,看起来就像在纸上打印一样(您可以使用浏览器的打印预览功能查看差异)。如果想让文档看起来像在屏幕上呈现的那样,则应使用 MediaType.Screen。
背景颜色
背景色 设置是自定义渲染文档外观的重要功能。它允许开发人员指定输出文件中每页背景的填充颜色。默认情况下,该属性设置为透明,这意味着除非明确指定,否则背景将不会有可见的填充。自定义背景颜色可以提高文档的可读性、满足品牌要求或创建具有视觉吸引力的设计。
1// Render HTML to PDF with custom background color using Java
2
3// Prepare HTML code and save it to a file
4String code = "<p>Hello, World!!</p>";
5try (java.io.FileWriter fileWriter = new java.io.FileWriter("document.html")) {
6 fileWriter.write(code);
7}
8
9// Create an instance of the HTMLDocument class
10HTMLDocument document = new HTMLDocument("document.html");
11
12// Initialize options with 'cyan' as a background-color
13PdfRenderingOptions options = new PdfRenderingOptions();
14options.setBackgroundColor(Color.getCyan());
15
16// Create an instance of the PdfDevice class
17PdfDevice device = new PdfDevice(options, "output.pdf");
18
19// Render HTML to PDF
20document.renderTo(device);页面设置
页面设置是一组决定打印页面布局的参数。这些参数包括从页面大小、页边距、自动调整大小到 @ 页面优先规则等所有内容。使用这组参数,你可以轻松地为每一页设置单独的布局。
在某些情况下,HTML 页面的内容可能比选项定义的页面尺寸更宽。如果不想截断页面内容,可以使用
PageSetup 类中的 AdjustToWidestPage 功能。下面的示例展示了如何根据内容调整页面大小。
1// Render HTML to PDF and adjust to the widest page with Java
2
3// Prepare HTML code
4String code = " <style>\n" +
5 " div {\n" +
6 " page - break -after:always;\n" +
7 " }\n" +
8 " </style >\n" +
9 " <div style = 'border: 1px solid red; width: 400px' > First Page</div >\n" +
10 " <div style = 'border: 1px solid red; width: 600px' > Second Page</div >\n";
11// Initialize an HTML document from HTML code
12HTMLDocument document = new HTMLDocument(code, ".");
13
14// Create an instance of the PdfRenderingOptions class and set a custom page-size
15PdfRenderingOptions options = new PdfRenderingOptions();
16options.getPageSetup().setAnyPage(new Page(new Size(500, 200)));
17
18// Enable auto-adjusting for the page size
19options.getPageSetup().setAdjustToWidestPage(true);
20
21// Create an instance of the PdfDevice class and specify options and output file
22PdfDevice device = new PdfDevice(options, "output.pdf");
23
24// Render HTML to PDF
25document.renderTo(device);PDF 选项
在将 HTML 转换为 PDF 时, PdfRenderingOptions 类为开发人员提供了对渲染过程的广泛控制。该类允许自定义所有常规选项,此外,它还提供了仅适用于 PDF 格式渲染的特定选项–DocumentInfo、Encryption、FormFieldBehaviour 和 JpegQuality。
下面的示例演示了为 PDF 文件设置权限的功能。
1// Render HTML to PDF with password protection using Java
2
3// Prepare HTML code
4String code = "<div>Hello, World!!</div>";
5
6// Initialize an HTML document from the HTML code
7HTMLDocument document = new HTMLDocument(code, ".");
8
9// Create the instance of the PdfRenderingOptions class
10PdfRenderingOptions options = new PdfRenderingOptions();
11
12// Set file permissions
13options.setEncryption(
14 new PdfEncryptionInfo(
15 "user_pwd",
16 "owner_pwd",
17 PdfPermissions.PrintDocument,
18 PdfEncryptionAlgorithm.RC4_128
19 )
20);
21
22// Create a PDF Device and specify options and output file
23PdfDevice device = new PdfDevice(options, "output.pdf");
24
25// Render HTML to PDF
26document.renderTo(device);图像选项
通过 ImageRenderingOptions,您可以自定义从平滑(抗锯齿)、图像分辨率、格式到图像压缩等多种设置。下面的示例演示了如何更改生成图像的分辨率和抗锯齿:
1// Render HTML to JPG with custom resolution and antialiasing settings with Java
2
3// Prepare HTML code
4String code = "<div>Hello, World!!</div>";
5
6// Initialize an instance of the HTMLDocument class based on prepared code
7HTMLDocument document = new HTMLDocument(code, ".");
8
9// Create an instance of the ImageRenderingOptions class
10ImageRenderingOptions options = new ImageRenderingOptions();
11options.setFormat(ImageFormat.Jpeg);
12
13// Disable smoothing mode
14options.setSmoothingMode(SmoothingMode.None);
15
16// Set the image resolution as 75 dpi
17options.setVerticalResolution(Resolution.fromDotsPerInch(75));
18options.setHorizontalResolution(Resolution.fromDotsPerInch(75));
19
20// Create an instance of the ImageDevice class
21ImageDevice device = new ImageDevice(options, "output.jpg");
22
23// Render HTML to Image
24document.renderTo(device);渲染器
虽然
Document类的
renderTo(device)方法使您能够向输出呈现设备发送单个文档,但直接使用
Renderer实例,您可以一次发送多个文件。Aspose.HTML for Java 提供了以下呈现器实现:
HtmlRenderer、
SvgRenderer、
MhtmlRenderer 和
EpubRenderer,它们分别用于渲染 HTML、SVG、MHTML 和 EPUB 文档。
下一个示例演示了如何使用 HtmlRenderer 渲染多个 HTML 文档:
1// Merge HTML to PDF using Java
2
3// Prepare HTML code
4String code1 = "<br><span style='color: green'>Hello, World!!</span>";
5String code2 = "<br><span style='color: blue'>Hello, World!!</span>";
6String code3 = "<br><span style='color: red'>Hello, World!!</span>";
7
8// Create three HTML documents to merge later
9HTMLDocument document1 = new HTMLDocument(code1, ".");
10HTMLDocument document2 = new HTMLDocument(code2, ".");
11HTMLDocument document3 = new HTMLDocument(code3, ".");
12
13// Create an instance of HTML Renderer
14HtmlRenderer renderer = new HtmlRenderer();
15
16// Create an instance of the PdfDevice class
17PdfDevice device = new PdfDevice("output.pdf");
18
19// Merge all HTML documents to PDF
20renderer.render(device, new HTMLDocument[]{document1, document2, document3});设置超时
渲染器还有一项重要功能,那就是超时设置。你可以用它来指定准备等待与文档生命周期相关的所有内部流程(如资源加载、活动计时器等)完成的时间。当然,您可以指定无限的等待时间。但是,如果文档包含一个无休止循环的脚本,您将无限期地等待。下面的示例演示了如何使用带有 timeout 参数的
render(device, timeout, documents) 方法:
1// Render HTML to PDF with timeout settings using Java
2
3// Prepare HTML code
4String code = "< script >\n" +
5 " var count = 0;\n" +
6 " setInterval(function()\n" +
7 " {\n" +
8 " var element = document.createElement('div');\n" +
9 " var message = (++count) + '. ' + 'Hello, World!!';\n" +
10 " var text = document.createTextNode(message);\n" +
11 " element.appendChild(text);\n" +
12 " document.body.appendChild(element);\n" +
13 " },1000);\n" +
14 "</script >\n";
15
16// Initialize an HTML document based on prepared HTML code
17HTMLDocument document = new HTMLDocument(code, ".");
18
19// Create an instance of HTML Renderer
20HtmlRenderer renderer = new HtmlRenderer();
21
22// Create an instance of the PdfDevice class
23PdfDevice device = new PdfDevice("output.pdf");
24
25// Render HTML to PDF
26renderer.render(device, 5, document);结论
Aspose.HTML for Java 是一个强大而灵活的库,可将 HTML、MHTML、EPUB 和 SVG 呈现为 PDF、XPS、DOCX 和图像等各种格式。对于简单的任务,Converter 类既快速又易于使用。但是,如果您需要对呈现选项进行更多控制,请使用 renderTo(device) 方法。
通过广泛的呈现选项和可配置功能,开发人员可以完全控制输出,包括分辨率、页面设置、CSS 媒体类型和特定设备配置。API 的灵活性体现在可以使用多个呈现器、配置常规和特定格式选项,甚至管理超时,因此是创建高质量定制文档的最佳选择。