Search code examples
c#itext7html-to-pdf

htmlConverter in itext7 closes the pdf document before I want it to be closed in C#


I'm using iText7 to convert from HTML to PDF which runs perfectly

however this call:

   HtmlConverter.ConvertToPdf(htmlStream, document);

will close the document after it's called but I don't want to close the document yet for the following reason

I wrote this function to write pages I'll be calling it in a loop

   public static void WritePage(string htmlbody)
    {
        document.AddNewPage();
        byte[] htmlByteArray = Encoding.UTF8.GetBytes(htmlbody); 
        MemoryStream htmlStream = new MemoryStream(htmlByteArray);       
        HtmlConverter.ConvertToPdf(htmlStream, document);
    }

and after the loop is over I'll close the document my self

 public static void CloseDocument()
    {   
       document.Close();
    }

this worked when I was using iText5 but now the convertToPdf will close the document. I can read from that document and add it with the new page to a new document but I don't want to do that I want to utilize the built in document.AddNewPage and after the document is fully constructed I'll close it myself

Thank you in advance


Solution

  • answer#1 is using PdfMerger and it is my preferred answer

    public void createPdf(String baseUri, String[] src, String dest) throws IOException { 
    ConverterProperties properties = new ConverterProperties();
    properties.setBaseUri(baseUri);
    PdfWriter writer = new PdfWriter(dest);
    PdfDocument pdf = new PdfDocument(writer);
    PdfMerger merger = new PdfMerger(pdf);
    for (String html : src) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfDocument temp = new PdfDocument(new PdfWriter(baos));
        HtmlConverter.convertToPdf(new FileInputStream(html), temp, properties);
        temp = new PdfDocument(
            new PdfReader(new ByteArrayInputStream(baos.toByteArray())));
        merger.merge(temp, 1, temp.getNumberOfPages());
        temp.close();
    }
    pdf.close();}
    

    answer#2 is converting the html to IElement List and adding that to the document like in follwoing code:

    public void createPdf(String baseUri, String[] src, String dest) throws IOException { 
    ConverterProperties properties = new ConverterProperties();
    properties.setBaseUri(baseUri);
    PdfWriter writer = new PdfWriter(dest);
    PdfDocument pdf = new PdfDocument(writer);
    Document document = new Document(pdf);
    for (String html : src) {
        List<IElement> elements =
            HtmlConverter.convertToElements(new FileInputStream(html), properties);
        for (IElement element : elements) {
            document.add((IBlockElement)element);
        }
    }
    document.close();}
    

    Reference: https://developers.itextpdf.com/content/itext-7-converting-html-pdf-pdfhtml/chapter-7-frequently-asked-questions-about-pdfhtml/how-parse-multiple-html-files-one-pdf