博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
合并PDF(保留其本身的大小)
阅读量:4297 次
发布时间:2019-05-27

本文共 2292 字,大约阅读时间需要 7 分钟。

在将多个PDF文件合并为一个PDF文件时,通常会创建一个新的 Document 对象,并读取每一个PDF文件的 PdfImportedPage 页,而后使用 PdfCopy 类中的方法将其添加到新创建的PDF文件中,部分代码如下:

for (int i = 0; i < fileList.size(); i++) {   PdfReader reader = new PdfReader(fileList.get(i));       int n = reader.getNumberOfPages();       for (int j = 1; j <= n; j++) {             document.newPage();              PdfImportedPage page = copy.getImportedPage(reader, j);              copy.addPage(page);       } }

但是,这种方式可能会破坏多个PDF文件的大小和旋转角度,如合并的PDF文件中有A4大小的和A3大小的,或者存在横向和纵向的。

为了保留原始文件的各种状态,可以参考下面的方法:

public static boolean concatPdfs(String[] originPaths, String targetPath) {        PdfCopyFields copyFields = null;        FileOutputStream outputStream = null;        PdfReader reader = null;        boolean result = true;        try {            File targetFile = new File(targetPath);            if (targetFile.exists() && targetFile.isFile()){                result = targetFile.delete();            }            if (result) {                outputStream = new FileOutputStream(targetFile);                copyFields = new PdfCopyFields(outputStream);                for (String pdfPath : originPaths) {                    File pdfFile = new File(pdfPath);                    if (!pdfFile.exists() || !pdfFile.isFile()) {                        System.out.println("file is not exist or is not a file.");                        return false;                    }                    reader = new PdfReader(pdfPath);                    copyFields.addDocument(reader);                    reader.close();                }            }            return result;        } catch (Exception e) {            e.printStackTrace();            return false;        } finally {            try {                if (copyFields != null) {                    copyFields.close();                }            } catch (Exception e) {                e.printStackTrace();            }            try {                if (outputStream != null) {                    outputStream.close();                }            } catch (Exception e) {                e.printStackTrace();            }            try {                if (reader != null) {                    reader.close();                }            } catch (Exception e) {                e.printStackTrace();            }        }    }

转载地址:http://wtdws.baihongyu.com/

你可能感兴趣的文章
文章索引-Android
查看>>
USB相机调试经历(Windows)
查看>>
“_ConnectionPtr”: 未声明的标识符。
查看>>
文章索引~ Visual C++
查看>>
tr1::shared_ptr 代码范例
查看>>
C++的四种强制转换
查看>>
cvWaitKey源码的理解(OpenCV函数)
查看>>
MFC的未来
查看>>
Windows窗口风格~Windows Style
查看>>
GDI贴图闪烁解决方法
查看>>
PreCreateWindow
查看>>
MFC类的范例: CArchive
查看>>
MFC类的范例:CComboBoxEx
查看>>
CDC
查看>>
CDialog上建立View的方法
查看>>
VC++ 操作Word
查看>>
(搬运工)推荐!国外程序员整理的 C++ 资源大全
查看>>
MFC消息处理流程
查看>>
在MFC中,如何获取CWinApp,CMainFrame,CChildFrame,CDocument,CView
查看>>
响应MFC Feature Pack中 CMFCRibbonCategory 切换消息
查看>>