Splitting a PDF file
mergeandcount
JAVA
JAVA
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2023 Apryse Group NV
Authors: Apryse Software.
For more information, please contact iText Software at this address:
sales@itextpdf.com
*/
package com.itextpdf.samples.sandbox.merge;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.utils.PageRange;
import com.itextpdf.kernel.utils.PdfSplitter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
public class MergeAndCount {
public static final String DEST = "./target/sandbox/merge/splitDocument1_%s.pdf";
public static final String RESOURCE = "./src/main/resources/pdfs/Wrong.pdf";
public static void main(String[] args) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new MergeAndCount().manipulatePdf(DEST);
}
protected void manipulatePdf(final String dest) throws IOException {
PdfDocument pdfDoc = new PdfDocument(new PdfReader(RESOURCE));
List<PdfDocument> splitDocuments = new PdfSplitter(pdfDoc) {
int partNumber = 1;
@Override
protected PdfWriter getNextPdfWriter(PageRange documentPageRange) {
try {
return new PdfWriter(String.format(dest, partNumber++));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
}.splitBySize(200000);
for (PdfDocument doc : splitDocuments) {
doc.close();
}
pdfDoc.close();
}
}
C#
C#
using System;
using System.Collections.Generic;
using System.IO;
using iText.Kernel.Pdf;
using iText.Kernel.Utils;
namespace iText.Samples.Sandbox.Merge
{
public class MergeAndCount
{
public static readonly String DEST = "results/sandbox/merge/splitDocument1_{0}.pdf";
public static readonly String RESOURCE = "../../../resources/pdfs/Wrong.pdf";
public static void Main(String[] args)
{
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new MergeAndCount().ManipulatePdf(DEST);
}
protected void ManipulatePdf(String dest)
{
PdfDocument pdfDoc = new PdfDocument(new PdfReader(RESOURCE));
IList<PdfDocument> splitDocuments = new CustomPdfSplitter(pdfDoc, dest).SplitBySize(200000);
foreach (PdfDocument doc in splitDocuments)
{
doc.Close();
}
pdfDoc.Close();
}
private class CustomPdfSplitter : PdfSplitter
{
private String dest;
private int partNumber = 1;
public CustomPdfSplitter(PdfDocument pdfDocument, String dest) : base(pdfDocument)
{
this.dest = dest;
}
protected override PdfWriter GetNextPdfWriter(PageRange documentPageRange) {
return new PdfWriter(String.Format(dest, partNumber++));
}
}
}
}