2017-04-06 117 views
0

我试图将html转换为java的aspose单词中的pdf文档。 (版本是17.4.0)从HTML转换为PDF时定义PageSize

我的问题是: 如何在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×297毫米),顶部边距也不为0.

任何人都可以告诉我如何在我的html中定义这个值?

回答

1

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

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

我是Tilal,Aspose的开发人员传福音。

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); 
+0

感谢您的回答。如果我使用你的代码,文件看起来是正确的。我的希望是,我可以在我的HTML中设置所有需要的布局功能。 –

+0

是的,在HTML中设置页面布局属性不会影响HTML到PDF的转换结果。 –