问题描述
我有一个HTML字符串,我需要将其转换为pdf,但是我需要的pdf必须具有特定的大小和边距.我以示例显示的方式进行操作,现在我有了可以设置宽度和高度的pdf,但是我无法更改或删除边距,所以请帮帮我.
I have an HTML string, i need to convert it to pdf, but pdf that i need must have specific size and margin. I did as the example show, now i have pdf with width and height that i set, BUT i can`t change or delete the margin, so pls help me.
using (FileStream fs = new FileStream(somePDFFile, FileMode.OpenOrCreate, FileAccess.Write))
{
iText.Kernel.Pdf.PdfWriter pdfWriter = new iText.Kernel.Pdf.PdfWriter(fs);
iText.Kernel.Pdf.PdfDocument pdfDoc = new iText.Kernel.Pdf.PdfDocument(pdfWriter);
var v = pdfDoc.GetDefaultPageSize().ApplyMargins<iText.Kernel.Geom.Rectangle>(1, 1, 1, 1, true);
pdfDoc.GetDefaultPageSize().SetWidth(250f);
pdfDoc.GetDefaultPageSize().SetHeight(200f);
pdfDoc.GetCatalog().SetLang(new iText.Kernel.Pdf.PdfString("en-US"));
//Set the document to be tagged
pdfDoc.SetTagged();
iText.Html2pdf.ConverterProperties props = new iText.Html2pdf.ConverterProperties();
iText.Html2pdf.HtmlConverter.ConvertToPdf(htmlString, pdfDoc, props);
pdfDoc.Close();
}
推荐答案
我在寻找答案,但是我只能找到这种方法:
I searched for an answer, but I could only find this approach:
public void createPdf(String src, String dest) throws IOException {
ConverterProperties properties = new ConverterProperties();
properties.setBaseUri(new File(src).getParent());
List<IElement> elements =
HtmlConverter.convertToElements(new FileInputStream(src), properties);
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.setTagged();
Document document = new Document(pdf);
document.setMargins(100, 50, 50, 100);
for (IElement element : elements) {
document.add((IBlockElement)element);
}
document.close();
}
换句话说:我将HTML转换为元素列表,然后将这些元素添加到为其定义边距的Document
中.
In other words: I convert the HTML to a list of elements, and I then add those elements to a Document
for which I define a margin.
我的首选解决方案是按照不幸的是,我注意到尚不支持此功能(我为iText开发团队提供了一张票证,以供其使用.解决此问题.)
我也尝试了convertToDocument()
方法,但是我无法将immediateFlush
设置为false.我还要求团队对此进行调查.
也许还有一个可以引入的属性,尽管我不确定这应该是ConverterProperties
属性,PdfDocument
属性还是PdfWriter
属性.
You could use the @page rule in CSS to define the margins. For instance:
<style>
@page {
margin-top: 200pt;
}
</style>
This creates a PDF with a top margin of 200pt.
这篇关于iText 7无法设置边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!