【问题标题】:Define PageSize when converting from HTML to PDF从 HTML 转换为 PDF 时定义 PageSize
【发布时间】:2017-04-06 10:29:51
【问题描述】:

我正在尝试将 html 转换为 pdf 文档,用 java 的 aspose 单词。 (版本为 17.4.0)

我的问题是: 如何在html中设置页面大小和页边距?

documentation 中,听起来我必须为部分(div 元素)设置宽度、高度和边距。

我的 html 看起来像这样:

<!DOCTYPE html>
<html>

<head>
    <title>Hello PDF</title>
</head>

<body>
    <div class="page" style="width:210mm; height:297mm; margin-top:0cm; margin-bottom:1cm; margin-left:1cm; margin-right:1cm;">
        <p>Hello World</p>
    </div>
</body>

</html>

我的java代码:

String baseUri = "path/to/doc/";

LoadOptions loadOptions = new LoadOptions();
loadOptions.setEncoding(Charset.forName("UTF-8"));
Document doc = new Document(baseUri + "test.html", loadOptions);

OutputStream outputStream = new FileOutputStream(baseUri + "test.pdf");
doc.save(outputStream, SaveFormat.PDF);

我的问题是生成的 pdf 的页面大小为 215,9 x 279,4 毫米(而不是 210 x 297 毫米),并且顶部的边距也不为 0。

谁能告诉我如何在我的 html 中定义这些值?

【问题讨论】:

    标签: java html pdf aspose aspose.words


    【解决方案1】:

    请注意,Aspose.Words 模仿与 MS Word 相同的行为。您的页面设置在 HTML 中很好。如果您在 MS Word 中加载输入 html 并将其转换为 PDF,它将生成页面大小为 215,9 x 279,4mm 的文档。

    但是,您可以使用 Aspose.Words API 根据您的要求更改部分的页面设置,如下所示。

    我是 Aspose 的开发布道师 Tilal。

    String baseUri = "path/to/doc/";
    
    LoadOptions loadOptions = new LoadOptions();
    loadOptions.setEncoding(Charset.forName("UTF-8"));
    com.aspose.words.Document doc = new com.aspose.words.Document(baseUri +"test.html", loadOptions);
    
    for (Section sectoin : doc.getSections())
    {
           PageSetup ps = sectoin.getPageSetup();
           ps.setPaperSize(PaperSize.A4);
           ps.setTopMargin(0.0);
           ps.setBottomMargin(1.0);
           ps.setLeftMargin(1.0);
           ps.setRightMargin(1.0);
    
    }
    
    OutputStream outputStream = new FileOutputStream(baseUri +"Test.pdf");
    doc.save(outputStream, com.aspose.words.SaveFormat.PDF);
    

    【讨论】:

    • 感谢您的回答。如果我使用您的代码,则文档看起来正确。我的希望是,我可以在我的 html 中设置所有需要的布局功能。
    • 是的,在 HTML 中设置页面布局属性不会影响 HTML 到 PDF 的转换结果。
    猜你喜欢
    • 2022-03-07
    • 1970-01-01
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 2010-12-31
    • 1970-01-01
    • 2011-12-28
    相关资源
    最近更新 更多