java使用itextpdf生成pdf文件

一、引入相关jar包

<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>

二、使用itextpdf生成pdf文件

2.1 创建目标文档

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 创建pdf文件中的章节

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 创建pdf文件中章节下的小节

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 向pdf文档中的小节下添加文本内容

/**
 * 添加文本内容到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 向pdf文档中添加image图片

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 向pdf文档中添加html内容

html文档解析器: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("
"
, "
"
).replace("
"
, "
"
).replace("", "").replace("", "").replace("", "");//不支持单独标签 p.parse(new ByteArrayInputStream(html.getBytes())); return elements; } }
String htmlContent = "

; 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;"> 海航回应HU7380航班返航】6月9日,海南航空从三亚飞往北京的HU7380航班起飞后,因飞机驾驶舱风挡玻璃出现裂纹,返航备降三亚凤凰机场。海航方面回应,此次事件未造成人员伤亡,该航班已经于当天20点14分重新起飞飞往北京。

; 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日,海南航空从三亚飞(0, 0, 0);">往北京的HU7380航班起飞后,因飞机驾驶舱风挡玻璃出现裂纹,返航备降三亚凤凰机场。海航方面回应,此次事件未造成人员伤亡,该航班已经于当天2;">0点14分重新起飞飞往北京。


;"/>

"
; ElementList elementList = WebXMLWorkerHelper.parseToElementList(htmlContent, null); for (Element element : elementList) { section.add(element); }

你可能感兴趣的:(java)