Converting HTML to PDF using iText

后端 未结 2 1984
面向向阳花
面向向阳花 2020-11-22 01:53

I am posting this question because many developers ask more or less the same question in different forms. I will answer this question myself (I am the Founder/CTO of iText G

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 02:40

    Use iText 7 and this code:

    public void generatePDF(String htmlFile) {
        try {
    
            //HTML String
            String htmlString = htmlFile;
            //Setting destination 
            FileOutputStream fileOutputStream = new FileOutputStream(new File(dirPath + "/USER-16-PF-Report.pdf"));
    
            PdfWriter pdfWriter = new PdfWriter(fileOutputStream);
            ConverterProperties converterProperties = new ConverterProperties();
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);
    
            //For setting the PAGE SIZE
            pdfDocument.setDefaultPageSize(new PageSize(PageSize.A3));
    
            Document document = HtmlConverter.convertToDocument(htmlFile, pdfDocument, converterProperties);
            document.close();
        } 
        catch (Exception e) {
             e.printStackTrace();
        }
    

    }

提交回复
热议问题