Java uses itextpdf to generate pdf files

1. Introduce related jar packages

<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itextpdf</artifactId>
	<version>5.5.13</version>
</dependency>
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itext-asian</artifactId>
	<version>5.2.0</version>
</dependency>	
<dependency>
	<groupId>com.itextpdf.tool</groupId>
	<artifactId>xmlworker</artifactId>
	<version>5.5.13</version>
</dependency>

Second, use itextpdf to generate pdf files

2.1 Create target document

public String createDocument(String folderName,String fileName,Document document)
            throws IOException {
    
    
    	     String pdfPath = "/data/pdfFile"; 
        // 如果文件夹不存在 则创建文件夹
        File folder = new File(pdfPath);
        if (!folder.exists()) {
    
    
            folder.mkdirs();
        }
        folder.createNewFile();
        String path = folder.getAbsolutePath();
        // 存储文件
        File file = new File(path, fileName);
        FileOutputStream out = null;
        try {
    
    
            out = new FileOutputStream(file);
            PdfWriter pdfWriter = PdfWriter.getInstance(document, out);
            pdfWriter.setStrictImageSequence(true); 
        } catch (FileNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (DocumentException e) {
    
    
            e.printStackTrace();
        }
        // 打开文档准备写入内容
        document.open();
        return pdfPath;
    }

2.2 Create chapters in pdf file

public static Chapter createChapter(String title, int chapterNum, int alignment, int numberDepth, Font font) {
    
    
        Paragraph chapterTitle = new Paragraph(title, font);
        chapterTitle.setAlignment(alignment);
        Chapter chapter = new Chapter(chapterTitle, chapterNum);
        chapter.setNumberDepth(numberDepth);
        return chapter;
}

2.3 Create the subsections under the chapters in the pdf file

public static Section createSection(Chapter chapter, String title, Font font, int numberDepth) {
    
    
        Section section = null;
        if (chapter != null) {
    
    
            Paragraph sectionTitle = new Paragraph(title, font);
            sectionTitle.setSpacingBefore(SPACING);
            section = chapter.addSection(sectionTitle);
            section.setNumberDepth(numberDepth);
        }
        return section;
}

2.4 Add text content to the subsections in the pdf document

/**
 * 添加文本内容到pdf文档中
 * text 文本内容
 * font 定义内容的字体
 */
public static Phrase createPhrase(String text, Font font) {
    
    
        Phrase phrase = new Paragraph(text, font);
        return phrase;
}
// 定义内容的字体
Font phraseFont = PDFUtil.createChineseFont(9, Font.NORMAL, new BaseColor(0, 0, 0));

String content = "此处一大段文本。。。。。。";
Phrase phraseCentent = PDFUtils.createPhrase(content, phraseFont);

// 将文本内容添加到pdf文档的小节中
section.add(phraseCentent);

2.5 Add image picture to pdf document

Image pic = Image.getInstance(new URL("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png");
//设置图片高度、宽度
pic.scaleToFit(pic.getWidth() / 2, pic.getHeight() / 2);
pic.setWidthPercentage(20);
pic.setScaleToFitHeight(true);
pic.setScaleToFitLineWhenOverflow(true);
// 将图片添加pdf文档中的小节中
section.add(pic);

2.6 Add html content to the pdf document

html document parser: WebXMLWorkerHelper

public class WebXMLWorkerHelper {
    
    

	
	public static class MyFontsProvider extends XMLWorkerFontProvider {
    
    
        public MyFontsProvider() {
    
    
            super(null, null);
        }
 
        @Override
        public Font getFont(final String fontname, String encoding, float size, final int style) {
    
    
            try {
    
    
                BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);//中文字体
                return new Font(bfChinese, size, style);
            } catch (Exception ex) {
    
    
                return new Font(Font.FontFamily.UNDEFINED, size, style);
            }
        }
    }
 
    public static ElementList parseToElementList(String html, String css) throws IOException {
    
    
        // CSS
        CSSResolver cssResolver = new StyleAttrCSSResolver();
        if (css != null) {
    
    
            CssFile cssFile = XMLWorkerHelper.getCSS(new ByteArrayInputStream(css.getBytes()));
            cssResolver.addCss(cssFile);
        }
 
        // HTML
        MyFontsProvider fontProvider = new MyFontsProvider();
        CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
        htmlContext.autoBookmark(false);
 
        // Pipelines
        ElementList elements = new ElementList();
        ElementHandlerPipeline end = new ElementHandlerPipeline(elements, null);
        HtmlPipeline htmlPipeline = new HtmlPipeline(htmlContext, end);
        CssResolverPipeline cssPipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
 
        // XML Worker
        XMLWorker worker = new XMLWorker(cssPipeline, true);
        XMLParser p = new XMLParser(worker);
        html = html.replace("<br>", "<br/>").replace("<hr>", "<hr/>").replace("<img>", "").replace("<param>", "").replace("<link>", "");//不支持单独标签
        p.parse(new ByteArrayInputStream(html.getBytes()));
        return elements;
    }
	
}
String htmlContent = "<p style="margin-top: 0px; margin-bottom: 15px; padding: 3px 0px; width: 600px; text-align: left; word-break: break-all; line-height: 1.8em; color: rgb(102, 102, 102); font-family: 微软雅黑; font-size: 18px; letter-spacing: 1px; white-space: normal; background-color: rgb(255, 255, 255); text-indent: 2em;">
    <strong>海航回应HU7380航班返航】6月9日,海南航空从三亚飞往北京的HU7380航班起飞后,因飞机驾驶舱风挡</strong>玻璃出现裂纹,返航备降三亚凤凰机场。海航方面回应,此次事件未造成人员伤亡,该航班已经于当天20点14分重新起飞飞往北京。
</p><p style="margin-top: 0px; margin-bottom: 15px; padding: 3px 0px; width: 600px; text-align: left; word-break: break-all; line-height: 1.8em; color: rgb(102, 102, 102); font-family: 微软雅黑; font-size: 18px; letter-spacing: 1px; white-space: normal; background-color: rgb(255, 255, 255); text-indent: 2em;">6月9日,海南航空从三亚飞<span style="border: 1px solid rgb(0, 0, 0);">往</span>北京的HU7380航班起飞后,因飞机驾驶舱风挡玻璃出现裂纹,返航备降三亚凤凰机场。海航方面回应,此次事件未造成人员伤亡,该航班已经于当天2<span style="text-indent: 2em;">0点14分重新起飞飞往北京。</span>
</p>
<p>
    <br style="text-align: left;"/>
</p>";
ElementList elementList = WebXMLWorkerHelper.parseToElementList(htmlContent, null);
for (Element element : elementList) {
    
    
    section.add(element);
}

Guess you like

Origin blog.csdn.net/ytangdigl/article/details/106657966