springboot 通过itextpdf生成pdf文件并进行下载

其中包括:生成标题,导入图片,以及导入字体展示特殊的编码☑,块,短语,段落的使用

(不适用单选框的原因是:

pdf中有动态增加行,无法固定按钮的坐标,如果单选框的位置固定,可以使用单选框的方式)

效果图如下:

java代码:

pom文件

 <!--pdf jar包-->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.4.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

PDFUtil

import com.alibaba.fastjson.JSONArray;
import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.taxagentgeneralticketplatfrom.param.declarationform.ConfirmDeclarationForm;

import java.awt.*;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import java.util.Map;

public class PDFUtil {
    public static void main(String[] args) throws IOException {
        String filename = "D:\\Program Files\\pdfTest\\testTable3.pdf";
        createPDF(filename);
        System.out.println("打印完成");
    }
    //定义全局的字体静态变量
    private static Font titlefont;
    private static Font headfont;
    private static Font headbody;
    private static Font keyfont;
    private static Font textfont;
    private static Font imageFont;
    // 最大宽度
    private static int maxWidth = 360;
    // 静态代码块
    static {
        try {
            // 不同字体(这里定义为同一种字体:包含不同字号、不同style)
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            //引入特殊字符的字体
            BaseFont baseFont = BaseFont.createFont("E:\\workspace\\taxagentgeneralticketplatform\\src\\main\\resources\\font\\msgothic.ttc,0",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
            imageFont = new Font(baseFont);
            titlefont = new Font(bfChinese, 14, Font.BOLD);
            headfont = new Font(bfChinese, 12, Font.BOLD);
            headbody = new Font(bfChinese, 12, Font.NORMAL);
            keyfont = new Font(bfChinese, 10, Font.BOLD);
            textfont = new Font(bfChinese, 10, Font.NORMAL);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void createPDF(String filename) throws IOException {
        Document document = new Document(PageSize.A4);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
            document.addTitle("example of PDF");
            document.open();
            // 段落
            Paragraph paragraph = new Paragraph("pdf表格模板", titlefont);
            paragraph.setAlignment(1); //设置文字居中 0靠左   1,居中     2,靠右
            paragraph.setIndentationLeft(12); //设置左缩进
            paragraph.setIndentationRight(12); //设置右缩进
            paragraph.setFirstLineIndent(24); //设置首行缩进
            //paragraph.setLeading(50f); //行间距
            paragraph.setSpacingBefore(5f); //设置段落上空白
            paragraph.setSpacingAfter(10f); //设置段落下空白
            document.add(paragraph);

            Chunk chunk1 = new Chunk("是");
            chunk1.setFont(headbody);
            Chunk chunk2 = new Chunk("☑");
            chunk2.setFont(imageFont);
            
            //增加块到文档
          /*  document.add(chunk1);
            document.add(chunk2);*/
            //短语
            Phrase phrase = new Phrase();
            phrase.add(chunk1);
            phrase.add(chunk2);
            Paragraph paragraph2 = new Paragraph(phrase);
            document.add(paragraph2);
            PdfPTable table = createTable(writer);
            //设置table的宽度并且锁定
            table.setTotalWidth(PageSize.A4.getWidth()-100);
            table.setLockedWidth(true);
            document.add(table);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
    //生成一个两列的表格
    public static PdfPTable createTable(PdfWriter writer) throws DocumentException, IOException{
        // 添加图片
        Image image = Image.getInstance("https://img2.baidu.com/it/u=1603121828,1164719810&fm=253&fmt=auto&app=138&f=JPEG?w=769&h=500");
        image.setAlignment(Image.ALIGN_CENTER);
        image.scalePercent(40); //依照比例缩放
        image.setAbsolutePosition(40,60);

        PdfPTable table = new PdfPTable(9);

        table.addCell(createCell("个人信息",textfont,1,1,3));
        table.addCell(createCell("名称",textfont,1,1));
        table.addCell(createCell("",textfont,1,3,1));
        table.addCell(createCell("照片",textfont,1,2,3));

        table.addCell(createCell(image,textfont,1,2,3));

        table.addCell(createCell("地址",textfont,1,1));
        table.addCell(createCell("",textfont,1,3,1));

        table.addCell(createCell("电话",textfont,1,1));
        table.addCell(createCell("",textfont,1,3,1));


        table.addCell(createCell("其他信息",textfont,1,1,3));
        table.addCell(createCell("名称",textfont,1,1));
        table.addCell(createCell("",textfont,1,3,1));
        table.addCell(createCell("身份证号",textfont,1,2,1));
        table.addCell(createCell("",textfont,1,2,1));
        table.addCell(createCell("地址",textfont,1,1));
        table.addCell(createCell("",textfont,1,3,1));
        table.addCell(createCell("开户银行",textfont,1,2,1));
        table.addCell(createCell("",textfont,1,2,1));
        table.addCell(createCell("电话",textfont,1,1));
        table.addCell(createCell("",textfont,1,3,1));
        table.addCell(createCell("银行账号",textfont,1,2,1));
        table.addCell(createCell("",textfont,1,2,1));

        table.addCell(createCell("类型",textfont,1,2,1));
        table.addCell(createCell("自然人",textfont,2,2,1,0,0,0,0));
        table.addCell(createCell("□",imageFont,0,1,1,0,0,0,0));
        table.addCell(createCell("其他纳税人",textfont,2,2,1,0,0,0,0));
        table.addCell(createCell("☑",imageFont,0,2,1,0,1,0,0));


        table.addCell(createCell("减免税标识",textfont,1,2,1));
        table.addCell(createCell("是",textfont,2,2,1,1,0,0,0));
        table.addCell(createCell("□",imageFont,0,1,1,1,0,0,0));
        table.addCell(createCell("否",textfont,2,2,1,1,0,0,0));
        table.addCell(createCell("☑",imageFont,0,2,1,1,1,0,0));


        table.addCell(createCell("受理税务机关",textfont,1,2,8));
        table.addCell(createCell("税务机关税款征收岗位",textfont,0,7,1,1,1,0,0));
        table.addCell(createCell("税收完税凭证号:",textfont,0,7,1,0,1,0,0));
        table.addCell(createCell("",textfont,1,3,1,0,0,0,0));
        table.addCell(createCell("(签字)",textfont,0,1,1,0,0,0,0));
        table.addCell(createCell("    年   月  日",textfont,1,3,1,0,1,0,0));

        table.addCell(createCell("税务机关代开发票岗位",textfont,0,7,1,1,1,0,0));
        table.addCell(createCell("发票代码:",textfont,0,7,1,0,1,0,0));
        table.addCell(createCell("发票号码:",textfont,0,7,1,0,1,0,0));
        table.addCell(createCell("(签字)",textfont,2,7,1,0,1,0,0));
        table.addCell(createCell("                  年        月       日  ",textfont,0,7,1,0,1,1,0));

        table.addCell(createCell("经办人",textfont,1,2,3));
        table.addCell(createCell("经核对,所开发票与申报单内容一致。",textfont,0,7,1,1,1,0,0));
        table.addCell(createCell(" ",textfont,0,3,1,0,0,0,0));
        table.addCell(createCell("经办人(签字):",textfont,0,4,1,0,1,0,0));
        table.addCell(createCell("                  年        月       日  ",textfont,2,7,1,0,1,1,0));

        return table;
    }

    /**------------------------创建表格单元格的方法start----------------------------*/
    public static PdfPCell createCell(Image image, Font font, int align, int colspan,int rowspan) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setRowspan(rowspan);
        cell.setFixedHeight(rowspan*25f);
        cell.setImage(image);
        // cell.setPhrase(new Phrase(new Chunk(image, 0, 0,false)));
        return cell;
    }
    public static PdfPCell createCell(Image image, Font font, int align, int colspan,int rowspan,int borderWidthTop,int borderWidthRight,int borderWidthBottom,int borderWidthLeft) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setRowspan(rowspan);
        cell.setFixedHeight(rowspan*25f);
        cell.setImage(image);
        //去除边框
        cell.setBorderWidthTop(borderWidthTop);
        cell.setBorderWidthRight(borderWidthRight);
        cell.setBorderWidthBottom(borderWidthBottom);
        cell.setBorderWidthLeft(borderWidthLeft);
        return cell;
    }
    /**
     * 创建单元格(指定字体)
     * @param value
     * @param font
     * @return
     */
    public static PdfPCell createCell(String value, Font font) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setPhrase(new Phrase(value, font));
        cell.setFixedHeight(25f);
        return cell;
    }
    /**
     * 创建单元格(指定字体、水平..)
     * @param value
     * @param font
     * @param align
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        cell.setFixedHeight(25f);
        return cell;
    }
    /**
     * 创建单元格(指定字体、水平居..、单元格跨x列合并)
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align, int colspan) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }
    public static PdfPCell createCell(String value, Font font, int align, int colspan,int rowspan) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setRowspan(rowspan);
        cell.setFixedHeight(rowspan*25f);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }
    public static PdfPCell createCell(String value, Font font, int align, int colspan,int rowspan,int borderWidthTop,int borderWidthRight,int borderWidthBottom,int borderWidthLeft) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setRowspan(rowspan);
        cell.setFixedHeight(rowspan*25f);
        cell.setPhrase(new Phrase(value, font));
        //去除边框
        cell.setBorderWidthTop(borderWidthTop);
        cell.setBorderWidthRight(borderWidthRight);
        cell.setBorderWidthBottom(borderWidthBottom);
        cell.setBorderWidthLeft(borderWidthLeft);
        return cell;
    }
    /**
     * 创建单元格(指定字体、水平居..、单元格跨x列合并、设置单元格内边距)
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @param boderFlag
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        cell.setPadding(3.0f);
        if (!boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(15.0f);
            cell.setPaddingBottom(8.0f);
        } else if (boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(0.0f);
            cell.setPaddingBottom(15.0f);
        }
        return cell;
    }
    /**
     * 创建单元格(指定字体、水平..、边框宽度:0表示无边框、内边距)
     * @param value
     * @param font
     * @param align
     * @param borderWidth
     * @param paddingSize
     * @param flag
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setFixedHeight(25f);
        cell.setPhrase(new Phrase(value, font));
        cell.setBorderWidthLeft(borderWidth[0]);
        cell.setBorderWidthRight(borderWidth[1]);
        cell.setBorderWidthTop(borderWidth[2]);
        cell.setBorderWidthBottom(borderWidth[3]);
        cell.setPaddingTop(paddingSize[0]);
        cell.setPaddingBottom(paddingSize[1]);
        if (flag) {
            cell.setColspan(2);
        }
        return cell;
    }
/**------------------------创建表格单元格的方法end----------------------------*/


/**--------------------------创建表格的方法start------------------- ---------*/


    /**
     * 创建默认列宽,指定列数、水平(居中、右、左)的表格
     * @param colNumber
     * @param align
     * @return
     */
    public static PdfPTable createTable(int colNumber, int align) {
        PdfPTable table = new PdfPTable(colNumber);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(align);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }
    /**
     * 创建指定列宽、列数的表格
     * @param widths
     * @return
     */
    public static PdfPTable createTable(float[] widths) {
        PdfPTable table = new PdfPTable(widths);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }
    /**
     * 创建空白的表格
     * @return
     */
    public static PdfPTable createBlankTable() {
        PdfPTable table = new PdfPTable(1);
        table.getDefaultCell().setBorder(0);
        table.addCell(createCell("", keyfont));
        table.setSpacingAfter(20.0f);
        table.setSpacingBefore(20.0f);
        return table;
    }
/**--------------------------创建表格的方法end------------------- ---------*/
}

总结问题:

1.导入字体的时候,提示找不到,解决方法如下:路径后面加上(,0)

 BaseFont baseFont = BaseFont.createFont("E:\\workspace\\taxagentgeneralticketplatform\\src\\main\\resources\\font\\msgothic.ttc,0",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
            

2.文本和特殊字符一起使用Paragraph该方法 易导致部分字符不显示,故使用 块:Chunk,短语:Phrase,段落:Paragraph的形式

            Chunk chunk1 = new Chunk("是");
            chunk1.setFont(headbody);
            Chunk chunk2 = new Chunk("☑");
            chunk2.setFont(imageFont);

            //增加块到文档
          /*  document.add(chunk1);
            document.add(chunk2);*/
            //短语
            Phrase phrase = new Phrase();
            phrase.add(chunk1);
            phrase.add(chunk2);
            Paragraph paragraph2 = new Paragraph(phrase);
            paragraph2.setAlignment(0); //设置文字居中 0靠左   1,居中     2,靠右
            paragraph2.setIndentationLeft(24); //设置左缩进
            paragraph2.setFirstLineIndent(12); //设置首行缩进
            paragraph2.setSpacingAfter(5f); //设置段落下空白
            document.add(paragraph2);

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot中接收MultipartFile图片并将其转换为PDF,并且使用iTextPDFPDF进行加密,你可以按照以下步骤进行操作: 1. 首先,确保你的项目中已经添加了iTextPDF的相关依赖。你可以在项目的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13.2</version> </dependency> ``` 2. 在你的控制器或服务类中,接收MultipartFile图片并将其转换为PDF,然后使用iTextPDFPDF进行加密,如下所示: ```java import com.itextpdf.text.Document; import com.itextpdf.text.pdf.PdfWriter; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; @RestController public class FileController { @PostMapping("/convertAndEncrypt") public void convertAndEncrypt(@RequestParam("file") MultipartFile file) { try { // 将MultipartFile转换为InputStream InputStream inputStream = file.getInputStream(); // 创建PDF文档 Document document = new Document(); OutputStream outputStream = new FileOutputStream("converted.pdf"); PdfWriter writer = PdfWriter.getInstance(document, outputStream); // 打开文档 document.open(); // 将图片写入PDF文档 document.add(com.itextpdf.text.Image.getInstance(inputStream)); // 关闭文档 document.close(); // 使用iTextPDFPDF进行加密 PDFEncryptionUtil.encryptPdf("converted.pdf", "encrypted.pdf", "userPassword", "ownerPassword"); // 处理加密后的PDF文件,例如保存到本地或者返回给前端 } catch (Exception e) { e.printStackTrace(); } } } ``` 3. 创建一个名为`PDFEncryptionUtil`的工具类,并在其中实现对PDF文件的加密,如下所示: ```java import com.itextpdf.text.Document; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileOutputStream; import java.io.OutputStream; public class PDFEncryptionUtil { public static void encryptPdf(String inputFilePath, String outputFilePath, String userPassword, String ownerPassword) throws Exception { PdfReader reader = new PdfReader(inputFilePath); OutputStream outputStream = new FileOutputStream(outputFilePath); PdfStamper stamper = new PdfStamper(reader, outputStream); stamper.setEncryption(userPassword.getBytes(), ownerPassword.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128); stamper.close(); reader.close(); outputStream.close(); } } ``` 在上述代码中,`convertAndEncrypt`方法接收一个MultipartFile参数,将其转换为PDF并保存到本地,然后调用`PDFEncryptionUtil`工具类对生成PDF文件进行加密。 请注意,这只是一个简单的示例,你可以根据自己的需求进行修改和扩展。 希望对你有所帮助!如果还有其他问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值