java生成pdf文件

这篇具有很好参考价值的文章主要介绍了java生成pdf文件。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

  1. pom添加依赖

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.1</version>
        </dependency

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
  1. util工具类

package com.susu.util;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;

/**
 * pdf工具类
 */
public class PdfUtil extends PdfPageEventHelper {

    /**
     * 定义静态变量,用于生成水印文件名称
     */
    private final static String RESULT_FILE = "D:/pdf/a.pdf";
    /**
     * 页眉
     */
    public String header = "xxxx";

    /**
     * 文档字体大小,页脚页眉最好和文本大小一致
     */
    public int presentFontSize = 12;

    /**
     * 文档页面大小,最好前面传入,否则默认为A4纸张
     */
    public Rectangle pageSize = PageSize.A4;
    /**
     * 基础字体对象
     */
    public BaseFont bf = null;
    /**
     * 利用基础字体生成的字体对象,一般用于生成中文文字
     */
    public Font fontDetail = null;
    // 模板
    public PdfTemplate total;

    /**
     *  返回一个暂无数据的pdf文件
     **/
    public static void nullPdf(OutputStream out)throws MalformedURLException, IOException, DocumentException {
        //①建立com.lowagie.text.Document对象的实例。
        Document doc = new Document(PageSize.A4,20,20,30,30);
        PdfWriter instance = PdfWriter.getInstance(doc, out);
        //③打开文档。
        doc.open();

        //创建字体
        BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
        //字体对象
        //大小为10的正常字体
        Font size10font = new Font(baseFont,10,Font.NORMAL);
        //大小为12的粗体
        Font size14bold = new Font(baseFont,12,Font.BOLD);

        // 准备工作结束,进行文档内容填充:
        // 第一页,结算汇总信息
        doc.newPage();
        doc.add(new Paragraph("暂无数据",size10font));
        doc.close();
        instance.close();
    }

    /**
     *
     * @param str 字符串
     * @param font 字体
     * @param high 表格高度
     * @Param alignCenter 是否水平居中
     * @Param alignMidde  是否垂直居中
     * @return
     */
    public static PdfPCell mircoSoftFont(String str, Font font, int high, boolean alignCenter, boolean alignMidde){
        PdfPCell pdfPCell  = new PdfPCell(new Phrase(str,font));
        pdfPCell.setMinimumHeight(high);
        // 设置可以居中
        pdfPCell.setUseAscender(true);
        if (alignCenter){
            // 设置水平居中
            pdfPCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        }
        if (alignMidde){
            // 设置垂直居中
            pdfPCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        }
        return pdfPCell;
    }

    /**
     * 给pdf文件添加水印
     *
     * @param InPdfFile
     *            要加水印的原pdf文件路径
     * @param outPdfFile
     *            加了水印后要输出的路径
     * @param readpicturepath
     *            水印图片路径
     * @throws Exception
     */
    public static void addPdfMark(String InPdfFile, String outPdfFile, String readpicturepath) throws Exception {
        PdfReader reader = new PdfReader(InPdfFile);
        int pageSize = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outPdfFile));
        // 插入水印
        Image img = Image.getInstance(readpicturepath);
        img.setAbsolutePosition(0, 0);
        for (int i = 1; i <= pageSize; i++) {
            PdfContentByte under = stamp.getUnderContent(i);
            under.addImage(img);
        }
        stamp.close();// 关闭
        File tempfile = new File(InPdfFile);
        if (tempfile.exists()) {
            tempfile.delete();
        }
    }

    /**
     * paragraph的格式
     * @param paragraph
     * @param doc
     * @throws DocumentException
     */
    public static void geshi1(Paragraph paragraph, Document doc) throws DocumentException {// 段落的格式
        paragraph.setIndentationLeft(30);
        paragraph.setIndentationRight(30);
        paragraph.setFirstLineIndent(20f);
        paragraph.setSpacingAfter(10f);
        paragraph.setSpacingBefore(10f);
        doc.add(paragraph);
    }

    /**
     * 居中无边框的cell
     * @param cell
     * @param table
     * @throws DocumentException
     */
    public static void geshi2(PdfPCell cell, PdfPTable table) throws DocumentException {// 表格的格式
        cell.setBorder(PdfPCell.NO_BORDER);
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER);
        table.addCell(cell);
    }

    // 不居中无边框的cell
    public static void geshi12(PdfPCell cell, PdfPTable table) throws DocumentException {// 表格的格式
        cell.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cell);
    }

    // 居中有边框的cell
    public static void geshi22(PdfPCell cell, PdfPTable table) throws DocumentException {// 表格的格式
        cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell.setVerticalAlignment(PdfPCell.ALIGN_CENTER);
        table.addCell(cell);
    }

    // 居中有边框的cell
    public static void geshi32(PdfPCell cell, PdfPTable table) throws DocumentException {// 表格的格式
        cell.setColspan(3);
        cell.setBorder(0);
        table.addCell(cell);
    }

    /**
     *
     * TODO 文档打开时创建模板
     *
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
     */
    @Override
    public void onOpenDocument(PdfWriter writer, Document document) {
        // 共 页 的矩形的长宽高
        total = writer.getDirectContent().createTemplate(50, 50);
    }

    /**
     *
     * Creates a new instance of PdfReportM1HeaderFooter 构造方法.
     *  @param yeMei
     *            页眉字符串
     * @param presentFontSize
     *            数据体字体大小
     * @param pageSize
     */
    public PdfUtil(String yeMei, int presentFontSize, Rectangle pageSize) {
        this.header = yeMei;
        this.presentFontSize = presentFontSize;
        this.pageSize = pageSize;
    }


    /**
     *
     * TODO 关闭每页的时候,写入页眉,写入'第几页'这几个字。
     *
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
     */
    @Override
    public void onEndPage(PdfWriter writer, Document document) {

        try {
            if (bf == null) {
                bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            }
            if (fontDetail == null) {
                // 数据体字体
                fontDetail = new Font(bf, presentFontSize, Font.NORMAL);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 1.写入页眉
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(header, fontDetail), document.getPageSize().getRight()/2, document.getPageSize().getTop()-36, 0);
//          没有需要写页脚的需求,先注释起来,后续有需求再调试
//        2.写入前半部分的 第 X页/共
//        int pageS = writer.getPageNumber();
//        String foot1 = "第 " + pageS + " 页";
//        Phrase footer = new Phrase(foot1, fontDetail);

//        // 3.计算前半部分的foot1的长度,后面好定位最后一部分的'Y页'这俩字的x轴坐标,字体长度也要计算进去 = len
//        float len = bf.getWidthPoint(foot1, presentFontSize);

//        // 4.拿到当前的PdfContentByte
//        PdfContentByte cb = writer.getDirectContent();

//        // 5.写入页脚1,x轴就是(右margin+左margin + right() -left()- len)/2.0F 再给偏移20F适合人类视觉感受,否则肉眼看上去就太偏左了 ,y轴就是底边界-20,否则就贴边重叠到数据体里了就不是页脚了;注意Y轴是从下往上累加的,最上方的Top值是大于Bottom好几百开外的。
//        ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer, (document.rightMargin() + document.right() + document.leftMargin() - document.left() - len) / 2.0F + 20F, document.bottom() - 20, 0);
//
//        // 6.写入页脚2的模板(就是页脚的Y页这俩字)添加到文档中,计算模板的和Y轴,X=(右边界-左边界 - 前半部分的len值)/2.0F + len , y 轴和之前的保持一致,底边界-20
//        // 调节模版显示的位置
//        cb.addTemplate(total, (document.rightMargin() + document.right() + document.leftMargin() - document.left()) / 2.0F + 20F, document.bottom() - 20);

    }

    /**
     *
     * TODO 关闭文档时,替换模板,完成整个页眉页脚组件
     *
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
     */
    @Override
    public void onCloseDocument(PdfWriter writer, Document document) {
        // 7.最后一步了,就是关闭文档的时候,将模板替换成实际的 Y 值,至此,page x of y 制作完毕,完美兼容各种文档size。
        total.beginText();
        // 生成的模版的字体、颜色
        total.setFontAndSize(bf, presentFontSize);
        String foot2 = " " + (writer.getPageNumber() - 1) + " 页";
        // 模版显示的内容
        total.showText(foot2);
        total.endText();
        total.closePath();
    }

    // 插入图片
    public static void addpicture(PdfPTable table, Image image, String picpath, PdfPCell cell, Document doc)
        throws MalformedURLException, IOException, DocumentException {
        image = Image.getInstance(picpath);
        cell = new PdfPCell(image);
        geshi2(cell, table);
        doc.add(table);
    }

    //非空判断
    public static String isnull(Object a) {
        if (a != null && a != "" && a != "null" && a.toString() != "null") {
            return a.toString();
        } else {
            return "";
        }
    }
}


  1. controller层,返回前端流数据,前端自己下载文件文章来源地址https://www.toymoban.com/news/detail-588440.html


        //①建立Document对象的实例。
        Document doc = new Document(PageSize.A4, 20, 20, 30, 30);
        //②建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
        String path = "D:\\test\\";
        String fileName = "test表.pdf";
        PdfWriter instance = PdfWriter.getInstance(doc, new FileOutputStream(path + fileName));
        PdfUtil pdfUtil = new PdfUtil(null, 15, PageSize.A4);
        //③打开文档。
        doc.open();
        pdfUtil.onOpenDocument(instance, doc);
        //创建字体
        BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        //字体对象
        //大小为10的正常字体
        Font size10font = new Font(baseFont, 10, Font.NORMAL);
        //大小为12的粗体
        Font size12font = new Font(baseFont, 12, Font.NORMAL);

        // 进行文档内容填充   第一行标题
        String titleName = "综合列表";
        PdfPTable table = new PdfPTable(header.size());
        table.setWidthPercentage(90);
        PdfPCell cell1 = new PdfPCell(new Phrase(titleName, size12font));
        cell1.setMinimumHeight(50);
        cell1.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        cell1.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        cell1.setColspan(header.size());
        cell1.setBorder(Rectangle.NO_BORDER);
        table.addCell(cell1);
        doc.add(table);


        //添加第1行的数据
        PdfPTable firstRowTable = new PdfPTable(header.size()); //三列的意思
        firstRowTable.setWidthPercentage(90);设置标题长度占纸张比例
        float[] widths = new float[]{5, 5, 5, 5, 5, 5, 5, 15, 23, 5, 13};
        firstRowTable.setWidths(widths);
        for (Map.Entry entry : header.entrySet()) {
            firstRowTable.addCell(PdfUtil.mircoSoftFont((String) entry.getValue(), size10font, 40, true, true));
        }
        doc.add(firstRowTable);

        //循环数据
        for (Map<String, Object> d : data) {
            //添加第2行的数据
            PdfPTable secondRowTable = new PdfPTable(header.size()); //三列的意思
            secondRowTable.setWidthPercentage(90);设置标题长度占纸张比例
            secondRowTable.setWidths(widths);
            for (Map.Entry entry : d.entrySet()) {
                secondRowTable.addCell(PdfUtil.mircoSoftFont((String) entry.getValue(), size10font, 40, true, true));
            }
            doc.add(secondRowTable);
        }
        pdfUtil.onEndPage(instance, doc);
        doc.close();
        instance.close();

        //把数据返给前端
        try {
            File file = new File(path + fileName);
            InputStream in = new BufferedInputStream(new FileInputStream(file));
            String filename = new String(fileName.getBytes(), "ISO8859_1");
            response.setContentType("application/binary;charset=ISO8859_1");
            response.setHeader("Content-disposition", "attachment; filename=" + filename);// 组装附件名称和格式
            IoUtil.copy(in, response.getOutputStream());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

到了这里,关于java生成pdf文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Java】使用iText生成PDF文件

    iText介绍 iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。 项目要使用iText,必须引入jar包。才能使用,maven依赖如下: 输出中文,还要引入下面itext-asian.jar包:  

    2024年02月10日
    浏览(27)
  • Java使用itextpdf生成PDF文件

    iText是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF文档,而且可以将Html文件转化为PDF文件。 构造方法: 指定PDF的页面大小,页边距。 默认 Document()为:A4,36,36,36,36 属性信息: 添加文字段落: 添加空页面: 是否显示空白页: 设置页面边距 构造方法: ll

    2024年01月19日
    浏览(31)
  • Java doc等文件生成PDF、多个PDF合并

    之前写过一遍文章是 图片生成PDF。 今天继续来对 doc等文件进行pdf合并以及多个pdf合并为一个pdf。 兄弟们,还是开箱即用。 依赖 示例代码 依赖 示例代码

    2024年02月10日
    浏览(32)
  • Java中如何生成PDF文件的缩略图

    在Java中生成PDF文件的缩略图可以使用Apache PDFBox库。以下是一个简单的示例代码来实现这个功能: 在上面的代码中,首先加载PDF文件并创建一个PDFRenderer对象。然后使用 renderImage 方法来渲染指定页面的PDF文档为一个BufferedImage对象。最后使用 writeImage 方法将BufferedImage对象保存

    2024年04月14日
    浏览(23)
  • nodejs根据pdf模板填入中文数据并生成新的pdf文件

    首先 const templateBytes = await fs.promises.readFile(templatePath);   const pdfDoc = await PDFDocument.load(templateBytes);   const form = pdfDoc.getForm(); 这三行表示读文件,并且读取pdf表单,然后注册fontkit,将你要的字体嵌入pdf中,之后在pdf的表单中寻找字段,填入字段,并把字体样式更新为你嵌入pd

    2024年02月10日
    浏览(33)
  • 功能需求-根据页面生成pdf,pdf不需要下载只需把文件流上传到服务器

    根据自身当下技术的水平和实际情况,做一个简单的记录。 在项目中有采购合同和销售合同,这些合同新建好之后都需要有人去审核,审核通过后需要把合同生成一个pdf文件然后后端给保存起来 在项目中有采购合同和销售合同,这些合同新建好之后都需要有人去审核,审核

    2024年02月13日
    浏览(32)
  • java 使用POI-TL根据word模版,生成word文件,含图片,富文本。

    1.引入mavna坐标` 2 .poi-tl-ext插件主要用于富文本内容格式在word展现 3.word模版创建 3.具体代码实现 4.本文的miniourl路径实质为网络路径的文件。

    2024年02月16日
    浏览(48)
  • 【PDFBox】PDFBox操作PDF文档之读取指定页面文本内容、读取所有页面文本内容、根据模板文件生成PDF文档

    这篇文章,主要介绍PDFBox操作PDF文档之读取指定页面文本内容、读取所有页面文本内容、根据模板文件生成PDF文档。 目录 一、PDFBox操作文本 1.1、读取所有页面文本内容 1.2、读取指定页面文本内容 1.3、写入文本内容 1.4、替换文本内容 (1)自定义PDTextStripper类 (2)创建Key

    2024年02月16日
    浏览(49)
  • Java使用ftl模板文件生成Word,以及Word转换图片或Pdf工具类

    一、写在前面 最近在项目中使用打印功能,发现这个功能我已经写过多次了,下面这个文章的发步日期在2020年,不得不感慨时间之快啊。 https://blog.csdn.net/weixin_43238452/article/details/109636200?spm=1001.2014.3001.5501 下面介绍一下应用场景:这次项目依旧是springboot项目,使用ftl模版生

    2024年02月15日
    浏览(42)
  • 【导出Word】如何使用Java+Freemarker模板引擎,根据XML模板文件生成Word文档(只含文本内容的模板)

    这篇文章,主要介绍如何使用Java+Freemarker模板引擎,根据XML模板文件生成Word文档。 目录 一、导出Word文档 1.1、基础知识 1.2、制作模板文件 1.3、代码实现 (1)引入依赖 (2)创建Freemarker工具类 (3)测试案例代码 (4)运行效果 Word文件有两种后缀格式,分别是:doc和docx,

    2024年02月13日
    浏览(45)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包