itextpdf PDF 文字、图片 签名

JAVA PDF 截取N页,生成新文件,转图片,多个PDF 合并

itextpdf PDF 文字、图片 签名


<itextpdf.version>5.5.13</itextpdf.version>
<itext-asian.version>5.2.0</itext-asian.version>

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>${itextpdf.version}</version>
</dependency>
<!--没有这个的话,添加文字会报错-->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>${itext-asian.version}</version>
</dependency>

public class PdfElementInfo {
    public enum TypeEnum {
        UNKNOWN,
        TEXT,
        IMAGE
    }

    /**
     * 1. 文本
     * 2. 图片
     */
    private int type;
    private float x;
    private float y;
    /**
     * 文本内容
     */
    private String text;
    private float fontSize;
    /**
     * 路径
     */
    private String imgPath;

   ...getter & setter....
}


    /**
     * 添加文字水印
     *
     * @param inputUrl
     * @param outputUrl
     * @param elementInfoList
     * @param pageRange       -1 全部,空:第一页,1:第一页,1~3:第1、2、3页
     */
    private void addElement(String inputUrl, String outputUrl, List<PdfElementInfo> elementInfoList, String... pageRange) {
        PdfStamper stamper = null;
        PdfReader reader = null;
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(outputUrl), false));
            reader = new PdfReader(inputUrl);
            stamper = new PdfStamper(reader, bos);
            int total = reader.getNumberOfPages() + 1;
            List<Integer> pageNumList = new ArrayList<>();
            if (pageRange.length == 0) {
                pageNumList.add(1);
            }
            if (pageNumList.size() > total) {
                throw new CustomException("指定页,超过了PDF文件页数");
            }
            PdfContentByte content;
            // BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            // "c:\\windows\\fonts\\SIMHEI.TTF" 使用windows系统的黑体
            BaseFont base = BaseFont.createFont("C:\\windows\\fonts\\SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            PdfGState gs = new PdfGState();
            for (Integer pageNum : pageNumList) {
                content = stamper.getOverContent(pageNum);// 在内容上方加水印
//                content = stamper.getUnderContent(pageNum);//在内容下方加水印
                gs.setFillOpacity(0.2f);
                content.beginText();
                //content.setTextMatrix(390, 810);
                //内容居中,横纵坐标,偏移量
                //content.showTextAligned(Element.ALIGN_CENTER, "AAAA", 179.54f, 718.62f, 0);
                for (PdfElementInfo textInfo : elementInfoList.stream().filter(p -> p.getType() == 1).collect(Collectors.toList())) {
                    //字体大小
                    content.setFontAndSize(base, textInfo.getFontSize());
                    content.showTextAligned(Element.ALIGN_CENTER, textInfo.getText(), textInfo.getX(), textInfo.getY(), 0);
                }

                for (PdfElementInfo imgInfo : elementInfoList.stream().filter(p -> p.getType() == 2).collect(Collectors.toList())) {
                    //添加图片
                    Image image = Image.getInstance(imgInfo.getImgPath());
                    /*
                      img.setAlignment(Image.LEFT | Image.TEXTWRAP);
                      img.setBorder(Image.BOX); img.setBorderWidth(10);
                      img.setBorderColor(BaseColor.WHITE); img.scaleToFit(100072);//大小
                      img.setRotationDegrees(-30);//旋转
                     */
                    //图片的位置(坐标)
                    image.setAbsolutePosition(imgInfo.getX(), imgInfo.getY());
                    // image of the absolute,宽、高,取最值值进行适配
                    image.scaleToFit(100, 100);
                    //image.scalePercent(imgInfo.getScalePercent());//依照比例缩放. 调整缩放,控制图片大小
                    content.addImage(image);
                }
                content.setFontAndSize(base, 8);
                content.endText();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (stamper != null) {
                    stamper.close();
                }
                //关闭打开的原来PDF文件,不执行reader.close()删除不了(必须先执行stamper.close(),否则会报错)
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Test
    void testSignature() throws Exception {

        String inputUrl = "D:\\THOTH\\0.SyncService\\Api.22586\\Report\\Report.pdf";
        //生成的文件路径
        String outputUrl = "D:\\THOTH\\0.SyncService\\Api.22586\\Report\\Report_out_" + DateUtil.current() + ".pdf";

        String imageUrl = "D:\\Users\\Pictures\\R-C.png";

        List<PdfElementInfo> elementInfoList = new ArrayList<>();

        PdfElementInfo textInfo = new PdfElementInfo();
        textInfo.setType(PdfElementInfo.TypeEnum.TEXT.ordinal());
        textInfo.setFontSize(10.5f);
        textInfo.setX(200f);
        textInfo.setY(100f);
        textInfo.setText("张三" + DateUtil.current());
        elementInfoList.add(textInfo);

        textInfo = new PdfElementInfo();
        textInfo.setType(PdfElementInfo.TypeEnum.TEXT.ordinal());
        textInfo.setFontSize(10.5f);
        textInfo.setX(400f);
        textInfo.setY(100f);
        textInfo.setText("李四" + DateUtil.current());
        elementInfoList.add(textInfo);


        PdfElementInfo imgInfo = new PdfElementInfo();
        imgInfo.setType(PdfElementInfo.TypeEnum.IMAGE.ordinal());
        imgInfo.setX(100f);
        imgInfo.setY(200f);
        imgInfo.setImgPath(imageUrl);
        elementInfoList.add(imgInfo);

        addElement(inputUrl, outputUrl, elementInfoList);
        //删除原来的PDF文件
            /*File targetTemplePDF = new File(inputPDFFilePath);
            targetTemplePDF.delete();*/
    }

image

posted @ 2024-12-31 15:22  VipSoft  阅读(41)  评论(0编辑  收藏  举报