欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 解析PDF

程序员文章站 2022-07-13 13:35:12
...

用java读取PDF,这里用到了itext,jar包可以自己上网下载:

 

	public static void readPDF(String path) throws Exception {
		try {

			PdfReader reader = new PdfReader(path);
			int n = reader.getNumberOfPages();
			System.out.println("page number = " + n);
			String str = PdfTextExtractor.getTextFromPage(reader, n); // Extracting
			System.out.println(str);
		} catch (Exception e) {
			System.out.println(e);
		}
	}

用java写入PDF:

 

	public static void writePDF(String path) {
		Document d = new Document();
		try {
			FileOutputStream os = new FileOutputStream(path);
			PdfWriter.getInstance(d, os);
			d.open();
			d.add(new Paragraph("hello PDF"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			d.close();
		}
	}

 往PDF中插入图片,图片格式不一样,插入方法略有不同:

 

	public static void writeImageToPDFWithPNG(String filePath, String imagePath) {

		try {
			// Create Document Object
			Document convertPngToPdf = new Document();
			// Create PdfWriter for Document to hold physical file
			// Change the PDF file path to suit to your needs
			PdfWriter.getInstance(convertPngToPdf, new FileOutputStream(
					filePath));
			convertPngToPdf.open();
			// Get the PNG image to Convert to PDF
			// getImage of PngImage class is a static method
			// Edit the file location to suit to your needs
			Image convertBmp = PngImage.getImage(imagePath);
			// Add image to Document
			convertPngToPdf.add(convertBmp);
			// Close Document
			convertPngToPdf.close();
			System.out
					.println("Converted and stamped PNG Image in a PDF Document Using iText and Java");
		} catch (Exception i1) {
			i1.printStackTrace();
		}
	}

	public static void writeIamgeToPDFWithBMP(String filePath, String imagePath) {
		try {
			// Create Document Object
			Document convertBmpToPdf = new Document();
			// Create PdfWriter for Document to hold physical file
			PdfWriter.getInstance(convertBmpToPdf, new FileOutputStream(
					filePath));
			convertBmpToPdf.open();
			// Get the Bitmap image to Convert to PDF
			// getImage is a static method, does not require object
			Image convertBmp = BmpImage.getImage(imagePath);
			// Add image to Document
			convertBmpToPdf.add(convertBmp);
			// Close Document
			convertBmpToPdf.close();
			System.out.println("Successfully Converted BMP to PDF in iText");
		} catch (Exception i1) {
			i1.printStackTrace();
		}
	}

	public static void writeIamgeToPDFWithJEPG(String filePath, String imagePath) {
		Document doc = new Document();
		Image jpeg;
		try {
			PdfWriter.getInstance(doc, new FileOutputStream(filePath));
			doc.open();
			jpeg = Image.getInstance(imagePath);
			// 图片居中
			jpeg.setAlignment(Image.ALIGN_CENTER);
			doc.add(jpeg);
			doc.close();
			System.out.println("Successfully Converted JPEG to PDF in iText");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}