Java操作PDF,在PDF文件指定位置输出水印

摘要:
需要参考我的上一篇博客,定位PDF中的关键字,找出需要打印水印的坐标位置。--引入pdf--˃com.itextpdfitextpdf5.5.13打印水印java文件PDFDocHelper.javapackagecom.alphajuns.util;importcom.itextpdf.text.BaseColor;importcom.itextpdf.text.DocumentException;importcom.itextpdf.text.Element;importcom.itextpdf.text.pdf.BaseFont;importcom.itextpdf.text.pdf.PdfContentByte;importcom.itextpdf.text.pdf.PdfReader;importcom.itextpdf.text.pdf.PdfStamper;importjava.io.FileOutputStream;importjava.io.IOException;importjava.util.List;importjava.util.Map;/***@AuthorAlphaJunS*@Date19:252020/3/7*@Description文档帮助类*/publicclassPDFDocHelper{privatestaticBaseFontbase=null;//获取基础文字publicstaticBaseFontgetBaseFont()throwsDocumentException,IOException{if{try{base=BaseFont.createFont;}catch{base=BaseFont.createFont;}}returnbase;}//psw文件签名publicstaticStringsignPsw(StringoldPswFilePath,List˂Map˃reviews)throwsIOException,DocumentException{intpos=oldPswFilePath.lastIndexOf('.');//获取文件后缀Stringsuffix=oldPswFilePath.substring;//判断是否为pdf文件if(!

需要参考我的上一篇博客,定位PDF中的关键字,找出需要打印水印的坐标位置。

先说测试结果(PDF原件也是上一篇中的图片所示):

新生成的带有水印的PDF文件如下所示:

Java操作PDF,在PDF文件指定位置输出水印第1张

junit测试代码及输出:

Java操作PDF,在PDF文件指定位置输出水印第2张

maven配置文件

<!--引入pdf -->
    <dependency>
      <groupId>com.itextpdf</groupId>
      <artifactId>itextpdf</artifactId>
      <version>5.5.13</version>
    </dependency>

打印水印java文件PDFDocHelper.java

packagecom.alphajuns.util;

importcom.itextpdf.text.BaseColor;
importcom.itextpdf.text.DocumentException;
importcom.itextpdf.text.Element;
importcom.itextpdf.text.pdf.BaseFont;
importcom.itextpdf.text.pdf.PdfContentByte;
importcom.itextpdf.text.pdf.PdfReader;
importcom.itextpdf.text.pdf.PdfStamper;

importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.util.List;
importjava.util.Map;

/*** @Author AlphaJunS
 * @Date 19:25 2020/3/7
 * @Description 文档帮助类
 */
public classPDFDocHelper {
    private static BaseFont base = null;
    //获取基础文字
    public static BaseFont getBaseFont() throwsDocumentException, IOException {
        if (base == null) {
            try{
                base = BaseFont.createFont("/u01/config/simsun.ttc,1",  BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            } catch(Throwable th) {
                base = BaseFont.createFont("C:\WINDOWS\Fonts\SIMSUN.TTC,1",  BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            }
        }
        returnbase;
    }

    //psw文件签名
    public static String signPsw(String oldPswFilePath, List<Map<String, ?>> reviews) throwsIOException, DocumentException {
        int pos = oldPswFilePath.lastIndexOf('.');
        //获取文件后缀
        String suffix = oldPswFilePath.substring(pos + 1);
        //判断是否为pdf文件
        if (!"pdf".equals(suffix.toLowerCase())) {
            throw new RuntimeException("Not supported PSW file");
        }
        returnsignSinglePsw(oldPswFilePath, reviews);
    }

    //单个psw文件签名
    private static String signSinglePsw(String oldPswFilePath,List<Map<String, ?>> reviews) throwsIOException, DocumentException {
        String newPswPath =oldPswFilePath;
        int pos = oldPswFilePath.lastIndexOf('.');
        //获取文件后缀名
        String suffix = oldPswFilePath.substring(pos + 1);
        //生成新的文件路径
        newPswPath = oldPswFilePath.substring(0, pos) + ".PSW." +suffix;
        System.out.println("单个psw文件签名生成的新路径:" +newPswPath);

        PdfReader reader = newPdfReader(oldPswFilePath);
        FileOutputStream fout = newFileOutputStream(newPswPath);
        PdfStamper stp = newPdfStamper(reader, fout);

        //总页数
        System.out.println("PDF总页数:" +reader.getNumberOfPages());

        for (int i = 0; i <reader.getNumberOfPages(); ) {
            //需要从第一页开始,i放在循环中会报空指针异常
            i++;
            PdfContentByte content =stp.getOverContent(i);
            content.beginText();

            //设置字体及字号
            content.setFontAndSize(getBaseFont(), 10);

            Map<String, Object> review = (Map<String, Object>) reviews.get(reviews.size() - 1);
            addDeptReview(content, review);
            content.endText();
        }

        stp.close();
        //将输出流关闭
fout.close();
        reader.close();
        //文件读写结束
        System.out.println("PSW文件读写完毕");

        returnnewPswPath;
    }

    /*** @Author AlphaJunS
     * @Date 18:48 2020/3/7
     * @Description 添加水印
     * @paramcontent
     * @paramreview
     * @returnvoid
     */
    private static void addDeptReview(PdfContentByte content, Map<String, Object>review) {
        if (Integer.parseInt(String.valueOf(review.get("type"))) == 1) {
            content.setColorFill(BaseColor.BLUE);
        } else{
            content.setColorFill(BaseColor.RED);
        }
        //设置水印位置和内容
        String result = (String) review.get("result");
        System.out.println("水印内容:" +result);
        System.out.println("打印位置坐标:" + pswX[0] + "," + pswY[0]);
        content.showTextAligned(Element.ALIGN_LEFT, result, pswX[0], pswY[0], 0);
    }

    //打印水印坐标
    private static float[] pswY = {128};
    private static float[] pswX = {337};

}

免责声明:文章转载自《Java操作PDF,在PDF文件指定位置输出水印》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Odoo学习笔记(二)安装一个新模块软件版本控制中的版本号下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

妙招教你Office Word 2007文档另存为PDF文件[转]

我们大家都知道Microsoft Office Word 2007的文档可以另存为只读的PDF格式文件,但必须预先安装加载插件项。        今天电脑软件技术博客就在这里详细讲解下Microsoft Office Word 2007 文档另存为PDF格式文件的详细步骤: 第一:首先,您肯定得安装上Microsoft Office Office 200...

调用支付宝转账接口(单笔)

下面这几个类都是支付宝demo里面的,直接拿过来用就可以 using System.Web; using System.Text; using System.IO; using System.Net; using System; using System.Collections.Generic; namespace Com.Alipay { pu...

android获取Mac地址和IP地址

获取Mac地址实际项目中测试了如下几种方法:(1)设备开通Wifi连接,获取到网卡的MAC地址(但是不开通wifi,这种方法获取不到Mac地址,这种方法也是网络上使用的最多的方法) //根据Wifi信息获取本地Mac public static String getLocalMacAddressFromWifiInfo(Context cont...

kafka producer interceptor拦截器(五)

  producer在发送数据时,会经过拦截器和序列化,最后到达相应的分区。在经过拦截器时,我们可以对发送的数据做进步的处理。   要正确的使用拦截器需要以下步骤:     1.实现拦截器ProducerInterceptor的方法     2.在producer的prop中配置        prop.put("interceptor.classes",...

VB创建类模块DLL文件

最近需要调用MSCOMM32.OCX控件,但是ABAP调用过程中发现无法同时发送多条记录,则需调整实现方式:   a.创建DLL文件封装MSCOMM控件相关属性及方法   b.系统注册DLL文件   c.ABAP调用DLL文件相关属性及方法 这一部分内容主要是将VB类模块的创建过程记录下: 1.打开VB,创建ActiveX DLL文件   2.修改工程名为...

guava API整理

1,大纲 让我们来熟悉瓜娃,并体验下它的一些API,分成如下几个部分: Introduction Guava Collection API Guava Basic Utilities IO API Cache API 2,为神马选择瓜娃? 瓜娃是java API蛋糕上的冰激凌(精华) 高效设计良好的API. 被google的开发者设计,实现和使用。...