import com.ironsoftware.ironpdf.*;
import com.ironsoftware.ironpdf.render.*;
import java.io.IOException;
import java.nio.file.Paths;
// Apply your license key
License.setLicenseKey("YOUR-LICENSE-KEY");
// Set a log path
Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));
// Create a new ChromePdfRenderOptions object
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
// Set custom options for the generated PDF document (paper size, title, etc.)
renderOptions.setCustomPaperSizeInCentimeters(31.75, 50.80 );
renderOptions.setPrintHtmlBackgrounds(true);
renderOptions.setPaperOrientation(PaperOrientation.LANDSCAPE);
renderOptions.setTitle("My PDF Document Name");
renderOptions.setEnableJavaScript(true);
renderOptions.setWaitFor(new WaitFor(50)); // time in milliseconds
renderOptions.setCssMediaType(CssMediaType.SCREEN);
renderOptions.UseScaledRendering(100); // 100 is zoom percentage
renderOptions.setCreatePdfFormsFromHtml(true);
// Customize PDF Margins by specifying sizes in millimeters
renderOptions.setMarginTop(40);
renderOptions.setMarginBottom(40);
renderOptions.setMarginLeft(20);
renderOptions.setMarginRight(20);
// Render the HTML document as a PDF using the specified rendering options.
try {
PdfDocument pdf = PdfDocument.renderHtmlFileAsPdf("wikipedia.html", renderOptions);
pdf.saveAs(Paths.get("assets/wikipedia.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
HTML 至 PDF 的渲染設定
此程式碼範例展示了 IronPDF 為開發人員提供的將 HTML 內容轉換為 PDF 文件的強大功能和靈活性。
ChromePdfRenderOptions確保開發者能夠完全控制網頁轉換為 PDF 的方式。
透過ChromePdfRenderOptions類,開發人員可以自訂頁面邊距、指定頁面方向、新增註解、包含書籤、更改文件元資料、調整縮放比例、修改 CSS 規則集等等。 一旦定義了該類別的對象,就可以將其作為第二個(可選)參數提供給任何靜態 PDF 文件渲染方法( renderHtmlAsPdf 、 renderHtmlFileAsPdf和renderUrlAsPdf ),以改變 IronPDF 解釋網站內容的方式,以及在這些方法執行期間渲染 PDF 內容的方式。