itextpdf实践与问题


文章内容: PDF文档的处理以及碰到的问题


需求:合成图片到pdf文档

代码:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

public class MergeFileTest {
	
	public static void main(String[] args) throws Exception {
		mergeImage(
				getImage("D:/exercise/pic/lisi-01.png"), 
				readFile("D:/exercise/pdf/20161213-001.pdf"), 
				"D:/exercise/pdf/merged20161213-001.pdf");
	}
	
	/**
	 * 合并图片到pdf文档
	 * @param img
	 * @param document
	 * @param savePath
	 * @throws Exception
	 */
	public static void mergeImage(Image img, byte[] document, String savePath) throws Exception{
		PdfStamper stamper = new PdfStamper(
				getPdfReader(document), new FileOutputStream(savePath));		
		PdfContentByte content = stamper.getOverContent(1);
		
		content.addImage(img);
		System.out.println("Merge completed.");
		stamper.close();
	}
	
	private static Image getImage(String imgPath) throws Exception{
		//获取图片
		Image img = Image.getInstance(imgPath);
		//设置缩放比例
		img.scalePercent(20f);
		//设置位置
		img.setAbsolutePosition(156, 545);
		
		return img;
	}
	
	/**
	 * 读取文件
	 * @param filePath
	 * @return
	 */
	private static byte[] readFile(String filePath) {
		FileInputStream file=null;
		try {
			file = new FileInputStream(filePath);
			byte[] fileByte = new byte[file.available()];
			file.read(fileByte);
			
			return fileByte;
		} catch (Exception e) {
			System.out.println(String.format(
					"fail to read file [%s], exception=%s", filePath, e.getMessage()));
		}finally {
			try {
				file.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return null;
	}
	
	private static PdfReader getPdfReader(byte[] document) throws IOException{
		PdfReader pdfReader = new PdfReader(document);
		pdfReader.unethicalreading = true;
		
		return pdfReader;
	}
	
}


文档合并前:

itextpdf实践与问题_第1张图片


文档合并后:

itextpdf实践与问题_第2张图片


Tips : 为了不覆盖文字,请确保png图片背景透明

----------------------------------------------------------------------------------------------------------


依赖的jar配置如下:


		
			com.itextpdf
			itextpdf
			5.3.2
		
		
		
		    org.bouncycastle
		    bcprov-ext-jdk15on
		    1.51
		

问题一:读取被加密的PDF文档时报错:

com.itextpdf.text.exceptions.BadPasswordException:: PdfReader not opened with owner password (未设置加密密码)或是

com.itextpdf.text.exceptions.BadPasswordException: PdfReader not opened with owner passwor (设置正确加密密码后)

解决方案:

设置PdfReader的静态属性unethicalreading为true, 无需设置加密密码,示例代码:

	PdfReader pdfReader = new PdfReader(document);
	pdfReader.unethicalreading = true;




你可能感兴趣的:(java,itextpdf)