iText 7 can not set margin

我是研究僧i 提交于 2021-01-27 05:23:30

问题


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();



            }

回答1:


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();
}

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.

My preferred solution would have been to define the margin at the level of the <body> tag as done in How to margin the body of the page (html)? Unfortunately, I noticed that this isn't supported yet (and I made a ticket for the iText development team to fix this).

I also tried the convertToDocument() method, but I wasn't able to set immediateFlush to false. I also asked the team to look into this.

Maybe there's also a property that could be introduced, although I'm not all that sure if this should be a ConverterProperties property, a PdfDocument property, or a PdfWriter property.

Update:

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.



来源:https://stackoverflow.com/questions/47470197/itext-7-can-not-set-margin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!