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

IO流之copy PDF文件

程序员文章站 2022-04-09 08:05:12
...
package com.io;

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

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfStream;
import com.itextpdf.text.pdf.PdfWriter;

public class CopyFilePDF {

	public static void main(String[] args) {
		
		FileInputStream fileInputStream = null;
		ByteArrayOutputStream byteArrayOutputStream = null;
		FileOutputStream fileOutputStream = null;
		
		try {
			fileInputStream = new FileInputStream(new File("D:\\aa.pdf"));
			fileOutputStream = new FileOutputStream(new File("D:\\bb.pdf"));
			byteArrayOutputStream = new ByteArrayOutputStream();
			
			byte[] bytes = new byte[1024];
			
			int len;
			
			while ((len = fileInputStream.read(bytes)) != -1) {
				byteArrayOutputStream.write(bytes, 0, len);
			}
			
			byteArrayOutputStream.flush();
			
			Document document = new Document();
			PdfStream pdfStream = new PdfStream(byteArrayOutputStream.toByteArray());
			PdfWriter pdfWriter = PdfWriter.getInstance(document, fileOutputStream);
			pdfStream.toPdf(pdfWriter, fileOutputStream);
			pdfWriter.flush();
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != fileOutputStream) {
					fileOutputStream.close();
				}
				if (null != byteArrayOutputStream) {
					byteArrayOutputStream.close();
				}
				if (null != fileInputStream) {
					fileInputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

需要导入的jar包:
链接:https://pan.baidu.com/s/1tW5tiIQCWtoaJapMeJ1nZg
提取码:vnhv

相关标签: IO流