java中pdfbox处理pdf常用方法(读取、写入、合并、拆分、写文字、写图片)

这篇具有很好参考价值的文章主要介绍了java中pdfbox处理pdf常用方法(读取、写入、合并、拆分、写文字、写图片)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

本篇文档将介绍pdfbox处理pdf常用方法(读取、写入、合并、拆分、写文字、写图片)。

图中为pdfbox用到的包

java中pdfbox处理pdf常用方法(读取、写入、合并、拆分、写文字、写图片)

1.读取pdf

方法代码:

/**
     * 读取pdf中文字信息(全部)
     * @param inputFile
     * @return
     */
    public static String ReadPdf(String inputFile){
        //创建文档对象
        PDDocument doc =null;
        String content="";
        try {
            //加载一个pdf对象
            doc =PDDocument.load(new File(inputFile));
            //获取一个PDFTextStripper文本剥离对象  
            PDFTextStripper textStripper =new PDFTextStripper();
            content=textStripper.getText(doc);
            System.out.println("内容:"+content);
            System.out.println("全部页数"+doc.getNumberOfPages());  
            //关闭文档
            doc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

测试用例:

public static void main(String[] args) throws Exception {
        
        String content = ReadPdf("C:\\pdfFolder\\target.pdf");
        System.out.println("内容如下:\n" + content);

}
java中pdfbox处理pdf常用方法(读取、写入、合并、拆分、写文字、写图片)

2.写入pdf

2.1写文字

方法代码:

/**
     * 指定页插入一段文字
     * @param inputFilePath
     * @param outputFilePath
     * @param pageNum
     * @param message
     * @throws Exception
     */
    public static void InsertPageContent (String inputFilePath, String outputFilePath, Integer pageNum, String message) throws Exception {
        File inputPDFFile = new File(inputFilePath);
        File outputPDFFile = new File(outputFilePath);
        // the document
        PDDocument doc = null;
        try{
            doc = PDDocument.load(inputPDFFile);
            PDPageTree allPages = doc.getDocumentCatalog().getPages();
            PDFont font = PDType1Font.HELVETICA_BOLD;
            //字体大小
            float fontSize = 36.0f;
            PDPage page = (PDPage)allPages.get(pageNum - 1);
            PDRectangle pageSize = page.getMediaBox();
            float stringWidth = font.getStringWidth(message)*fontSize/1000f;
            // calculate to center of the page
            int rotation = page.getRotation(); 
            boolean rotate = rotation == 90 || rotation == 270;
            float pageWidth = rotate ? pageSize.getHeight() : pageSize.getWidth();
            float pageHeight = rotate ? pageSize.getWidth() : pageSize.getHeight();
            double centeredXPosition = rotate ? pageHeight/2f : (pageWidth - stringWidth)/2f;
            double centeredYPosition = rotate ? (pageWidth - stringWidth)/2f : pageHeight/2f;
            // append the content to the existing stream
            PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true,true);
            contentStream.beginText();
            // set font and font size
            contentStream.setFont( font, fontSize );
            // set text color to red
            contentStream.setNonStrokingColor(255, 0, 0);
            if (rotate) {
                // rotate the text according to the page rotation
                contentStream.setTextRotation(Math.PI/2, centeredXPosition, centeredYPosition);
            } else {
                contentStream.setTextTranslation(centeredXPosition, centeredYPosition);
            }
            contentStream.drawString(message);
            contentStream.endText();
            contentStream.close();
            doc.save(outputPDFFile);
            System.out.println("成功向pdf插入文字");
        } finally {
            if( doc != null ) {
                doc.close();
            }
        }
    }

测试用例:

    public static void main(String[] args) throws Exception {
        String inputFilePath = "C:\\pdfFolder\\A.pdf";
        String outputFilePath = "C:\\pdfFolder\\A2.pdf";
        //只能写英文,写中文会报错
        InsertPageContent(inputFilePath, outputFilePath, 1, "testMessage");
}

A.pdf:

java中pdfbox处理pdf常用方法(读取、写入、合并、拆分、写文字、写图片)

A2.pdf:

java中pdfbox处理pdf常用方法(读取、写入、合并、拆分、写文字、写图片)

2.2写图片

方法代码:

    /**
     * 在pdf中插入图片
     * @param inputFilePath
     * @param imagePath
     * @param outputFilePath
     * @param pageNum
     * @throws Exception
     */
    public static void insertImage(String inputFilePath, String imagePath, String outputFilePath, Integer pageNum) throws Exception {
        File inputPDFFile = new File(inputFilePath);
        File outputPDFFile = new File(outputFilePath);
        
        try {
            PDDocument doc = PDDocument.load(inputPDFFile);
            PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
    
            PDPage page = doc.getPage(0);
            //注释的这行代码会覆盖原内容,没注释的那行不会覆盖
//            PDPageContentStream contentStream = new PDPageContentStream(doc, page);
            PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true, true);
            contentStream.drawImage(pdImage, 70, 250);
            contentStream.close();
            doc.save(outputPDFFile);
            doc.close();
            System.out.println("成功插入图片");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

测试用例:

public static void main(String[] args) throws Exception {
        String inputFilePath = "C:\\pdfFolder\\A.pdf";
        String outputFilePath = "C:\\pdfFolder\\A2.pdf";
        String imagePath = "C:\\pdfFolder\\pic.jpg";
        insertImage(inputFilePath, imagePath, outputFilePath, 1);
}

A.pdf:

java中pdfbox处理pdf常用方法(读取、写入、合并、拆分、写文字、写图片)

pic.jpg:

A2.pdf:

3.合并pdf

方法代码:

    /**
     * 
     * @param pathList
     * @param targetPDFPath
     * @throws Exception
     */
    public static void MergePdf(List<String> pathList, String targetPDFPath) throws Exception {
        List<InputStream> inputStreams = new ArrayList<>();
        for(String path : pathList) {
            inputStreams.add(new FileInputStream(new File(path)));
        }
        PDFMergerUtility mergePdf = new PDFMergerUtility();
        File file = new File(targetPDFPath);
        
        if (!file.exists()) {
            file.delete();
        }
        
        mergePdf.addSources(inputStreams);
        mergePdf.setDestinationFileName(targetPDFPath);
        mergePdf.mergeDocuments();
        for (InputStream in : inputStreams) {
        if (in != null) {
            in.close();
            }
        }
    }

测试用例:

    public static void main(String[] args) throws Exception {
        List<String> pathList = new ArrayList<String>();
        String targetPDFPath = "C:\\pdfFolder\\target.pdf";
        pathList.add("C:\\pdfFolder\\A.pdf");
        pathList.add("C:\\pdfFolder\\B.pdf");
        pathList.add("C:\\pdfFolder\\C.pdf");
        pathList.add("C:\\pdfFolder\\D.pdf");
        pathList.add("C:\\pdfFolder\\E.pdf");
        
        MergePdf(pathList, targetPDFPath);
    }
java中pdfbox处理pdf常用方法(读取、写入、合并、拆分、写文字、写图片)

4.拆分pdf

方法代码:

/**
     * 将pdf逐页分割
     * @param sourcePdfPath
     * @param splitPath
     * @param splitFileName
     * @throws Exception
     */
    public static void SpiltPdf(String sourcePdfPath, String splitPath, String splitFileName) throws Exception {
        int j = 1;
        String splitPdf = splitPath + File.separator + splitFileName + "_";

        // Loading an existing PDF document
        File file = new File(sourcePdfPath);
        PDDocument document = PDDocument.load(file);
        // Instantiating Splitter class
        Splitter splitter = new Splitter();
        splitter.setStartPage(1);
        splitter.setSplitAtPage(1);
        splitter.setEndPage(5);
        // splitting the pages of a PDF document
        List<PDDocument> Pages = splitter.split(document);
        // Creating an iterator
        Iterator<PDDocument> iterator = Pages.listIterator();
        // Saving each page as an individual document
        while(iterator.hasNext()) {
            PDDocument pd = iterator.next();
            String pdfName = splitPdf + j++ + ".pdf";
            pd.save(pdfName);
        }
        document.close();
    }

测试用例:

public static void main(String[] args) throws Exception {
        String sourcePdfPath = ("C:\\pdfFolder\\target.pdf");
        String splitPath = ("C:\\pdfFolder");
        String splitFileName = ("splitPDF");
        spiltPdf(sourcePdfPath, splitPath, splitFileName);
}
java中pdfbox处理pdf常用方法(读取、写入、合并、拆分、写文字、写图片)

引用链接:

(17条消息) 使用Apache PDFBox实现拆分、合并PDF_似有风中泣的博客-CSDN博客

(17条消息) Java使用PDFBox操作PDF文件_pdfbox 打印 token_一个傻子程序媛的博客-CSDN博客

(17条消息) PDFbox基本操作_pdtype0font_静若繁花_jingjing的博客-CSDN博客文章来源地址https://www.toymoban.com/news/detail-507521.html

到了这里,关于java中pdfbox处理pdf常用方法(读取、写入、合并、拆分、写文字、写图片)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • java利用pdfbox动态生成PDF

    Apache PDFBox 是一个用于处理 PDF 文档的 Java 库。它提供了许多功能和方法来读取、创建、操作和提取 PDF 文档的内容。 PDDocument 类 引用源码中对PDDocument 类的描述 This is the in-memory representation of the PDF document 这是PDF文档的内存表示,在 java 程序中,你可以简单理解

    2024年02月06日
    浏览(34)
  • Java使用pdfbox将pdf转图片

    目前比较主流的两种转pdf的方式,就是pdfbox和icepdf,两种我都尝试了下,icepdf解析出来有时候会出现中文显示不出来,网上的解决方式又特别麻烦,不是安装字体,就是重写底层类,所以我选择了pdfbox 在windows上好好的,x86_64的linux上也好好的,就是arm架构的linux上会出现 网上

    2024年02月10日
    浏览(34)
  • JAVA 实现PDF转图片(pdfbox版)

    依赖: pdf存放路径 正文开始: pdf转换多张图片、长图 展示效果: 附加:小程序预览wxml代码 依赖: pdf存放路径 正文开始: pdf转换多张图片、长图

    2024年02月06日
    浏览(38)
  • Java使用pdfbox进行pdf和图片之间的转换

    pdfbox是Apache开源的一个项目,支持pdf文档操作功能。 官网地址: Apache PDFBox | A Java PDF Library 支持的功能如下图. 引入依赖

    2024年02月06日
    浏览(33)
  • Java 利用pdfbox将图片和成到pdf指定位置

    业务背景:用户在手机APP上进行签名,前端将签完名字的图片传入后端,后端合成新的pdf. 废话不多说,上代码: 注意:前端传过来的图片必须是透明的,否则合成的时候签名处会有边框        

    2024年02月09日
    浏览(39)
  • 如何通过Java的Apache PDFBox库制作一个PDF表格模板并填充数据

    要使用Java的Apache PDFBox库制作一个PDF表格模板并填充数据,你需要遵循以下步骤: 添加依赖 :首先,确保你的项目中包含了Apache PDFBox的依赖。如果你使用Maven,可以在你的 pom.xml 文件中添加以下依赖: 创建PDF模板 :你可以使用PDFBox创建一个简单的PDF模板,或者使用其他工具

    2024年02月22日
    浏览(34)
  • Java实现自动化pdf打水印小项目 使用技术pdfbox、Documents4j

    博主介绍:✌目前全网粉丝2W+,csdn博客专家、Java领域优质创作者,博客之星、阿里云平台优质作者、专注于Java后端技术领域。 涵盖技术内容:Java后端、算法、分布式微服务、中间件、前端、运维、ROS等。 博主所有博客文件目录索引:博客目录索引(持续更新) 视频平台:

    2024年02月20日
    浏览(42)
  • 【数据处理】Pandas读取CSV文件示例及常用方法(入门)

    查看读取前10行数据 2067 向前填充 指定列的插值填充 使用某数据填充指定列的空值 示例: 类似切片 array([‘SE’, ‘cv’, ‘NW’, ‘NE’], dtype=object) 类似数据库查询中的groupby查询 先添加新的一列按月将数据划分 聚合,对指定的列按月划分求平均值等 min 最小值 max 最大值 sum

    2024年02月06日
    浏览(42)
  • 100天精通Python(进阶篇)——第42天:pdfplumber读取pdf(基础+代码实战写入Excel)

    PDF(Portable Document Format)是一种便携文档格式,便于跨操作系统传播文档。PDF文档遵循标准格式,因此存在很多可以操作PDF文档的工具,Python自然也不例外。

    2023年04月12日
    浏览(32)
  • Scala编程 读取Kafka处理并写入Redis

            Kafka是一种分布式流处理平台,它是一个高吞吐量、可扩展、持久化的消息队列系统,用于处理实时数据流。 Kafka的核心概念包括生产者(Producer)、消费者(Consumer)和主题(Topic)。 生产者负责将数据发布到Kafka集群,消费者则从Kafka集群中订阅并消费数据。主

    2024年02月19日
    浏览(28)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包