Java如何使用Java向PDF頁面中新增文字?

2019-10-16 22:28:51

在Java程式設計中,如何使用Java向PDF頁面中新增文字?

以下是使用Java向PDF頁面中新增文字的範例程式。

package com.yiibai;

import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.PDType3Font;

public class AddText2PDF {
    public static void main(String args[]) throws IOException {
        // Creating PDF document object
        PDDocument document = new PDDocument();
        float version = document.getVersion();
        System.out.println("Version="+version);

        // Add an empty page to it
        document.addPage(new PDPage());

        // Saving the document
        document.save("F:/worksp/javaexamples/java_apache_pdf_box/AddText_IP.pdf");
        // Loading an existing document
        PDDocument doc = PDDocument.load(new File("F:/worksp/javaexamples/java_apache_pdf_box/AddText_IP.pdf"));

        // Creating a PDF Document
        PDPage page = doc.getPage(0);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page);

        // Begin the Content stream
        contentStream.beginText();

        // Setting the font to the Content stream
        contentStream.setFont( PDType1Font.TIMES_ROMAN, 16 ); 

        // Setting the position for the line
        contentStream.newLineAtOffset(25, 725);
        String text = "This is an example of adding text to a page in the pdf document.";

        // Adding text in the form of string
        contentStream.showText(text);

        // Ending the content stream
        contentStream.endText();
        System.out.println("Content added");

        // Closing the content stream
        contentStream.close();

        // Saving the document
        doc.save(new File("F:/worksp/javaexamples/java_apache_pdf_box/AddText_OP.pdf"));

        // Closing the document
        doc.close();

        System.out.println("All jobs done.");
    }
}

執行上面範例程式碼,得到以下結果 -

Version=1.4
Content added
All jobs done.

此時,程式已經建立一個新檔案:F:/worksp/javaexamples/java_apache_pdf_box/AddText_OP.pdf