Search code examples
itext7

How can I create In memory PDF byte from itextpdf without creating actual file in filesystem


I am refering to below code in itextpdf to create PDF from html. I have added iText core library and pdfHTML add-on to our project dependencies.

itext-html-to-pdf-using-java

import com.itextpdf.html2pdf.HtmlConverter;

public class App 
{
    public static final String HTML = "<h1>Hello</h1>"
            + "<p>This was created using iText</p>"
            + "<a href='hmkcode.com'>hmkcode.com</a>";
    
    
    public static void main( String[] args ) throws FileNotFoundException, IOException  
    {
        HtmlConverter.convertToPdf(HTML, new FileOutputStream("string-to-pdf.pdf"));
        
        System.out.println( "PDF Created!" );
    }
}

How can I create in memory pdf bytes without creating actual file in filesystem.

Thank you


Solution

  • I think you have partially answered the query itself.

    FileOutputStream is one of the way you can write your pdf bytes onto.

    https://api.itextpdf.com/pdfHTML/java/2.1.6/com/itextpdf/html2pdf/HtmlConverter.html

    Have a look at overloaded methods.

    You can write your pdf bytes onto ByteArrayOutputStream and use those as required. This will eliminate your need to save content as pdf file.

    Hope this helps.