多个pdf文件合并

向右看齐 2024-04-01 16:52 218阅读 0赞

使用maven引入jar包:

  1. <dependency>
  2. <groupId>com.lowagie</groupId>
  3. <artifactId>itext</artifactId>
  4. <version>2.1.7</version>
  5. </dependency>

可以使用工具类和测试Utile测试一下~

  1. import com.lowagie.text.Document;
  2. import com.lowagie.text.pdf.PdfCopy;
  3. import com.lowagie.text.pdf.PdfImportedPage;
  4. import com.lowagie.text.pdf.PdfReader;
  5. import java.io.FileOutputStream;
  6. public class PdfUtil {
  7. /**
  8. * 合并pdf
  9. * @param files 需要合并的pdf路径
  10. * @param newfile 合并成新的文件的路径
  11. */
  12. public static boolean mergePdfFiles(String[] files, String newfile) {
  13. boolean retValue = false;
  14. Document document = null;
  15. PdfCopy copy = null;
  16. PdfReader reader = null;
  17. try {
  18. document = new Document(new PdfReader(files[0]).getPageSize(1));
  19. copy = new PdfCopy(document, new FileOutputStream(newfile));
  20. document.open();
  21. for (int i = 0; i < files.length; i++) {
  22. reader = new PdfReader(files[i]);
  23. int n = reader.getNumberOfPages();
  24. for (int j = 1; j <= n; j++) {
  25. document.newPage();
  26. PdfImportedPage page = copy.getImportedPage(reader, j);
  27. copy.addPage(page);
  28. }
  29. reader.close();
  30. }
  31. retValue = true;
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. } finally {
  35. if (reader != null) {
  36. reader.close();
  37. }
  38. if (copy != null) {
  39. copy.close();
  40. }
  41. if (document != null) {
  42. document.close();
  43. }
  44. }
  45. return retValue;
  46. }
  47. public static void main(String[] args) {
  48. String[] files = {"D:\wanyi_az\Dict\a.pdf","D:\wanyi_az\Dict\b.pdf","D:\wanyi_az\Dict\c.pdf" };
  49. String savepath = "D:\wanyi_az\Dict\back.pdf";
  50. boolean b = mergePdfFiles(files, savepath);
  51. System.out.println(b);
  52. }
  53. }

发表评论

表情:
评论列表 (有 0 条评论,218人围观)

还没有评论,来说两句吧...

相关阅读