Java-OpenPDF、iText、PDFBox 三种常用 PDF处理库
OpenPDF、iText和PDFBox都是Java中用于处理PDF文件的库。以下是每个库的简单示例:
- OpenPDF(用于读取PDF):
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import java.io.File;
import java.io.IOException;
public class OpenPDFExample {
public static void main(String[] args) throws IOException {
try (PDDocument document = PDDocument.load(new File("example.pdf"))) {
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
System.out.println(text);
}
}
}
- iText(用于创建、修改PDF):
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import java.io.File;
import java.io.IOException;
public class iTextExample {
public static void main(String[] args) throws IOException {
PdfWriter writer = new PdfWriter("example.pdf");
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);
document.add(new Paragraph("Hello, World!"));
document.close();
pdf.close();
writer.close();
}
}
- PDFBox(用于创建、修改PDF):
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 java.io.File;
import java.io.IOException;
public class PDFBoxExample {
public static void main(String[] args) throws IOException {
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.beginText();
contentStream.setFont(PDType1Font.HELVETICA_BOLD);
contentStream.moveTextPositionByAmount(200, 700);
contentStream.drawString("Hello, World!");
contentStream.endText();
contentStream.close();
document.save("example.pdf");
document.close();
}
}
以上代码提供了读取、创建和编辑PDF文档的简单示例。每个库都有其特点和用途,开发者可以根据需要选择合适的库。
评论已关闭