Java使用PDFBox开发包实现对PDF文档内容编辑与保存

简介: Java使用PDFBox开发包实现对PDF文档内容编辑与保存

pdfbox开发包下载地址:http://pdfbox.apache.org/

程序实现了PDF文档的创建,读入,与修改PDF内容并保存。

可能有个前提,PDF文档不是加密的,如果加密怎么办,我没研究过!

源代码如下:

package com.gloomyfish.ups.pdf.reader;
 
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
 
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSString;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdfparser.PDFStreamParser;
import org.apache.pdfbox.pdfwriter.ContentStreamWriter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.util.PDFOperator;
import org.apache.pdfbox.util.PDFTextStripper;
 
/**
 * http://pdfbox.apache.org/
 * 
 * @author fish
 * 
 */
public class PDFReader {
  
  public PDFReader()
  {
    createHelloPDF();
    readPDF();
    editPDF();
  }
 
  public void createHelloPDF() {
    PDDocument doc = null;
    PDPage page = null;
 
    try {
      doc = new PDDocument();
      page = new PDPage();
 
      doc.addPage(page);
      PDFont font = PDType1Font.HELVETICA_BOLD;
      PDPageContentStream content = new PDPageContentStream(doc, page);
      content.beginText();
      content.setFont(font, 12);
      content.moveTextPositionByAmount(100, 700);
      content.drawString("Hello");
 
      content.endText();
      content.close();
      doc.save("D:\\gloomyfish\\pdfwithText.pdf");
      doc.close();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  
  public void readPDF()
  {
    PDDocument helloDocument;
    try {
      helloDocument = PDDocument.load(new File(
          "D:\\gloomyfish\\pdfwithText.pdf"));
      PDFTextStripper textStripper = new PDFTextStripper();
      System.out.println(textStripper.getText(helloDocument));
      helloDocument.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  
  public void editPDF() {
     
    try {
      // pdfwithText
      PDDocument helloDocument = PDDocument.load(new File("D:\\gloomyfish\\pdfwithText.pdf"));
      // PDDocument helloDocument = PDDocument.load(new File("D:\\gloomyfish\\hello.pdf"));
      // int pageCount = helloDocument.getNumberOfPages();
      PDPage firstPage = (PDPage)helloDocument.getDocumentCatalog().getAllPages().get(0);
      // PDPageContentStream content = new PDPageContentStream(helloDocument, firstPage);
      PDStream contents = firstPage.getContents();
      
      PDFStreamParser parser = new PDFStreamParser(contents.getStream());  
            parser.parse();  
            List tokens = parser.getTokens();  
            for (int j = 0; j < tokens.size(); j++)  
            {  
                Object next = tokens.get(j);  
                if (next instanceof PDFOperator)  
                {  
                  PDFOperator op = (PDFOperator) next;  
                    // Tj and TJ are the two operators that display strings in a PDF  
                    if (op.getOperation().equals("Tj"))  
                    {  
                        // Tj takes one operator and that is the string  
                        // to display so lets update that operator  
                        COSString previous = (COSString) tokens.get(j - 1);  
                        String string = previous.getString();  
                        string = string.replaceFirst("Hello", "Hello World, fish");  
                        //Word you want to change. Currently this code changes word "Solr" to "Solr123"  
                        previous.reset();  
                        previous.append(string.getBytes("ISO-8859-1"));  
                    }  
                    else if (op.getOperation().equals("TJ"))  
                    {  
                        COSArray previous = (COSArray) tokens.get(j - 1);  
                        for (int k = 0; k < previous.size(); k++)  
                        {  
                            Object arrElement = previous.getObject(k);  
                            if (arrElement instanceof COSString)  
                            {  
                                COSString cosString = (COSString) arrElement;  
                                String string = cosString.getString();  
                                string = string.replaceFirst("Hello", "Hello World, fish");  
                                
                                // Currently this code changes word "Solr" to "Solr123"  
                                cosString.reset();  
                                cosString.append(string.getBytes("ISO-8859-1"));  
                            }  
                        }  
                    }  
                }
            }
            // now that the tokens are updated we will replace the page content stream.  
            PDStream updatedStream = new PDStream(helloDocument);  
            OutputStream out = updatedStream.createOutputStream();  
            ContentStreamWriter tokenWriter = new ContentStreamWriter(out);  
            tokenWriter.writeTokens(tokens);  
            firstPage.setContents(updatedStream);  
            helloDocument.save("D:\\gloomyfish\\helloworld.pdf"); //Output file name  
            helloDocument.close();
//      PDFTextStripper textStripper = new PDFTextStripper();
//      System.out.println(textStripper.getText(helloDocument));
//      helloDocument.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (COSVisitorException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 
  public static void main(String[] args) {
    new PDFReader();
  }
}
相关文章
|
22天前
|
JavaScript Java 测试技术
Java项目基于ssm+vue.js的网上手机销售系统附带文章和源代码设计说明文档ppt
Java项目基于ssm+vue.js的网上手机销售系统附带文章和源代码设计说明文档ppt
25 0
|
9天前
|
Java
java处理pdf代码
java处理pdf代码
16 0
|
19天前
使用LabVIEW打开默认应用程序中的文档(PDF,Word,Excel,Html)
使用LabVIEW的&quot;Open a Document on Disk.vi&quot;,存于&lt;LabVIEW&gt;\vi.lib\Platform\browser.llb,可让默认应用打开硬盘文档。此VI仅基础打开功能,高级控制推荐LabVIEW Report Generation Toolkit或ActiveX。注意:避免版本升级问题,最好将VI复制到vi.lib外的目录。
|
10天前
|
数据可视化 Java API
【JAVA】javadoc,如何生成标准的JAVA API文档
【JAVA】javadoc,如何生成标准的JAVA API文档
10 0
|
17天前
|
Java
P9242 [蓝桥杯 2023 省 B] 接龙数列JAVA,边权为1的最短路问题,洛谷P9242 [蓝桥杯 2023 省 B] 接龙数列​编辑力扣1926.迷宫离入口最近的出口力扣433.
P9242 [蓝桥杯 2023 省 B] 接龙数列JAVA,边权为1的最短路问题,洛谷P9242 [蓝桥杯 2023 省 B] 接龙数列​编辑力扣1926.迷宫离入口最近的出口力扣433.
|
22天前
|
JavaScript Java 测试技术
Java项目基于ssm+vue.js的生鲜在线销售系统附带文章和源代码设计说明文档ppt
Java项目基于ssm+vue.js的生鲜在线销售系统附带文章和源代码设计说明文档ppt
15 0
|
2天前
|
安全 Java
JAVA多线程通信新解:wait()、notify()、notifyAll()的实用技巧
【6月更文挑战第20天】Java多线程中,`wait()`, `notify()`和`notifyAll()`用于线程通信。在生产者-消费者模型示例中,它们确保线程同步。`synchronized`保证安全,`wait()`在循环内防止虚假唤醒,`notifyAll()`避免唤醒单一线程问题。关键技巧包括:循环内调用`wait()`,优先使用`notifyAll()`以保证可靠性,以及确保线程安全和正确处理`InterruptedException`。
|
2天前
|
安全 Java
深入解读JAVA多线程:wait()、notify()、notifyAll()的奥秘
【6月更文挑战第20天】JAVA多线程中,wait(), notify(), notifyAll()是Object类的关键同步机制。wait()让线程等待并释放锁,直到被notify()或notifyAll()唤醒或超时。它们必须在同步块中使用,持有锁的线程调用。notify()唤醒一个等待线程,notifyAll()唤醒所有。最佳实践包括:与synchronized结合,循环检查条件,避免循环内notify(),通常优先使用notifyAll()。
|
2天前
|
Java 程序员
从菜鸟到大神:JAVA多线程通信的wait()、notify()、notifyAll()之旅
【6月更文挑战第21天】Java多线程核心在于wait(), notify(), notifyAll(),它们用于线程间通信与同步,确保数据一致性。wait()让线程释放锁并等待,notify()唤醒一个等待线程,notifyAll()唤醒所有线程。这些方法在解决生产者-消费者问题等场景中扮演关键角色,是程序员从新手到专家进阶的必经之路。通过学习和实践,每个程序员都能在多线程编程的挑战中成长。
|
1天前
|
安全 Java 程序员
Java多线程详解
Java多线程详解