Java:iText生成pdf文档

简介: Java:iText生成pdf文档

依赖

<!-- pdf:start -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.11</version>
</dependency>
<dependency>
    <groupId>com.itextpdf.tool</groupId>
    <artifactId>xmlworker</artifactId>
    <version>5.5.11</version>
</dependency>
<!-- 支持中文 -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>
<!-- 支持css样式渲染 -->
<dependency>
    <groupId>org.xhtmlrenderer</groupId>
    <artifactId>flying-saucer-pdf-itext5</artifactId>
    <version>9.1.16</version>
</dependency>
<!-- 转换html为标准xhtml包 -->
<dependency>
    <groupId>net.sf.jtidy</groupId>
    <artifactId>jtidy</artifactId>
    <version>r938</version>
</dependency>
<!-- pdf:end -->

使用示例

1、简单使用

package com.pengshiyu;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
/**
 * Hello world!
 */
public class PdfDemo {
    public static void main(String[] args) throws Exception {
    // 新建文档
        Document document = new Document(PageSize.A4);
        // 如果输出中文,需要设置中文字体
        BaseFont chineseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font font = new Font(chineseFont, 12, Font.NORMAL);
        PdfWriter.getInstance(document, new FileOutputStream("hello.pdf"));
        // 打开文档
        document.open();
        // 写入内容
        Paragraph paragraph = new Paragraph("hello world 你好世界", font);
        document.add(paragraph);
        // 关闭文档
        document.close();
    }
}

6.png

2、稍复杂的示例

package com.pengshiyu;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.codec.Base64;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.css.StyleAttrCSSResolver;
import com.itextpdf.tool.xml.html.CssAppliers;
import com.itextpdf.tool.xml.html.CssAppliersImpl;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.AbstractImageProvider;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
import java.io.*;
public class App {
    /**
     * 创建PDF文件
     *
     * @param htmlStr
     * @throws Exception
     */
    private static void writeToOutputStreamAsPDF(String htmlStr) throws Exception {
        String targetFile = "pdfDemo.pdf";
        File targeFile = new File(targetFile);
        if (targeFile.exists()) {
            targeFile.delete();
        }
        //定义pdf文件尺寸,采用A4横切
        Document document = new Document(PageSize.A4, 25, 25, 15, 40);// 左、右、上、下间距
        //定义输出路径
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(targetFile));
        // PdfReportHeaderFooter header = new PdfReportHeaderFooter("", 8, PageSize.A4);
        // writer.setPageEvent(header);
        writer.addViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
        document.open();
        // CSS
        CSSResolver cssResolver = new StyleAttrCSSResolver();
        CssAppliers cssAppliers = new CssAppliersImpl(new XMLWorkerFontProvider() {
            @Override
            public Font getFont(String fontname, String encoding, boolean embedded, float size, int style, BaseColor color) {
                try {
                    //用于中文显示的Provider
                    BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                    return new Font(bfChinese, size, style);
                } catch (Exception e) {
                    return super.getFont(fontname, encoding, size, style);
                }
            }
        });
        //html
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
        htmlContext.setImageProvider(new AbstractImageProvider() {
            @Override
            public Image retrieve(String src) {
                //支持图片显示
                int pos = src.indexOf("base64,");
                try {
                    if (src.startsWith("data") && pos > 0) {
                        byte[] img = Base64.decode(src.substring(pos + 7));
                        return Image.getInstance(img);
                    } else if (src.startsWith("http")) {
                        return Image.getInstance(src);
                    }
                } catch (BadElementException ex) {
                    return null;
                } catch (IOException ex) {
                    return null;
                }
                return null;
            }
            @Override
            public String getImageRootPath() {
                return null;
            }
        });
        // Pipelines
        PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
        HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
        CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
        // XML Worker
        XMLWorker worker = new XMLWorker(css, true);
        XMLParser p = new XMLParser(worker);
        p.parse(new ByteArrayInputStream(htmlStr.getBytes()));
        document.close();
    }
    /**
     * 读取 HTML 文件
     *
     * @return
     */
    private static String readHtmlFile() {
        StringBuffer textHtml = new StringBuffer();
        try {
            File file = new File("printDemo.html");
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            // 一次读入一行,直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                textHtml.append(tempString);
            }
            reader.close();
        } catch (IOException e) {
            return null;
        }
        return textHtml.toString();
    }
    public static void main(String[] args) throws Exception {
        // 读取html文件
        String htmlStr = readHtmlFile();
        // 将html文件转成PDF
        writeToOutputStreamAsPDF(htmlStr);
    }
}
<html>
<head></head>
<body>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>出库单</title>
<div>
    <div>
        <table width="100%" border="0" cellspacing="0" cellpadding="0">
            <tbody>
            <tr>
                <td height="40" colspan="2"><h3 style="font-weight: bold; text-align: center; letter-spacing: 5px; font-size: 24px;">入库单</h3></td>
                <td width="12%" height="20" rowspan="2">
                    <img style="width: 105px;height: 105px;" src="data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAH0AAAB9AQAAAACn+1GIAAAAqElEQVR42u3VMQ7DMAwDQP6A//8lx24qKRRw0s1yu8Uw4OQGIaHsBHUfLzzwAxCAInoZg6dI9dUUBIOyHEG56CmodAaxwtfbboLTVWpeU9+EDAH37m9CmkTYxDGUE0agMIakk3y4Ut8G37iom02M4bPniHWAtqFDTjjSGLrZvXAOmTnL1124C73r6Yo8Ane61k6eQeVjIM2h482D1RwScrpNjuH5R/0b3s6ZZNyKlt3iAAAAAElFTkSuQmCC" />
                </td>
            </tr>
            <tr>
                <td width="50%" height="30">操作人:xxx</td>
                <td width="50%" height="30" colspan="2">创建时间:2021-09-14 12:00:00</td>
            </tr>
            </tbody>
        </table>
    </div>
    <div style="margin-top: 5px; margin-bottom: 6px; margin-left: 4px"></div>
    <div>
        <table width="100%"
               style="border-collapse: collapse; border-spacing: 0;border:0px;">
            <tr style="height: 25px;">
                <td style="background: #eaeaea; text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;"
                    width="10%">序号</td>
                <td style="background: #eaeaea; text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;"
                    width="30%">商品</td>
                <td style="background: #eaeaea; text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;"
                    width="30%">单位</td>
                <td style="background: #eaeaea; text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-right: 1px solid #000000;"
                    width="30%">数量</td>
            </tr>
            <tr>
                <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">1</td>
                <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">xxx沐浴露</td>
                <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">箱</td>
                <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-right: 1px solid #000000;">3</td>
            </tr>
            <tr>
                <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">2</td>
                <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">xxx洗发水</td>
                <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">箱</td>
                <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-right: 1px solid #000000;">4</td>
            </tr>
            <tr>
                <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">3</td>
                <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">xxx洗衣粉</td>
                <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000;">箱</td>
                <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-right: 1px solid #000000;">5</td>
            </tr>
            <tr>
                <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-bottom: 1px solid #000000;">4</td>
                <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-bottom: 1px solid #000000;">xxx洗面奶</td>
                <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-bottom: 1px solid #000000;">箱</td>
                <td style="text-align: center; border-left: 1px solid #000000; border-top: 1px solid #000000; border-right: 1px solid #000000; border-bottom: 1px solid #000000;">5</td>
            </tr>
        </table>
    </div>
</div>
</body>
</html>

5.png

参考

手把手教你使用Java开发在线生成pdf文档

相关文章
|
6月前
|
Java
java Itext创建pdf
java Itext创建pdf
65 0
Java:iText生成pdf文档
Java:iText生成pdf文档
250 0
|
XML Java Apache
Java 生成PDF文档
最近项目需要实现PDF下载的功能,由于没有这方面的经验,从网上花了很长时间才找到相关的资料。整理之后,发现有如下几个框架可以实现这个功能。 1. 开源框架支持 iText,生成PDF文档,还支持将XML、Html文件转化为PDF文件; Apache PDFBox,生成、合并PDF文档; docx4j,生成docx、pptx、xlsx文档,支持转换为PDF格式。
11322 1
|
1月前
|
Java
Java PDF模板生成PDF
Java PDF模板生成PDF
30 1
|
5月前
|
Java
java处理pdf代码
java处理pdf代码
47 0
|
4月前
|
Java API Apache
如何在Java中实现PDF生成
如何在Java中实现PDF生成
|
XML Java 数据处理
java将excel转为pdf
在Java中,可以使用Apache POI库处理Excel文件,以及使用iText库将Excel文件转换为PDF格式。
1342 0
|
IDE Java 应用服务中间件
Java WebService如何生成PDF文件
在Web应用开发中,生成PDF文件是一项非常常见的需求。本文将介绍如何使用Java WebService来生成PDF文件。
123 0
java通过poi导出excel和pdf
由于各户的需求,所以需要增加导出excel这个功能,其实大部分系统都需要这个导出功能的,所以这里也就不详细说明具体导出的背景了O(∩_∩)O~
Java使用itext按模板生成PDF文件
Java使用itext按模板生成PDF文件