Reputation: 433
I want to cut out all pages of a PDF file that contain a special string (splittag). Until now I have this code but it just gives out all pages of the source PDF. So whats wrong with it? I iterate trough the Pages of the source PDF and check if the actual page contains the splittag, then create a new PDF using it for pagenumber. Would be great if someone could help. Thank you!
iTextSharp.text.PdfReader reader = new iTextSharp.text.PdfReader(textBox3.Text);
string splittag = textBox2.Text;
StringBuilder text = new StringBuilder();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
if(PdfTextExtractor.GetTextFromPage(reader, i, new SimpleTextExtractionStrategy()).ToString().Contains(splittag)) ;
{
richTextBox1.Text = PdfTextExtractor.GetTextFromPage(reader, i, new SimpleTextExtractionStrategy());
Document document = new Document();
PdfCopy copy = new PdfCopy(document, new FileStream(textBox5.Text + "\\" + i + ".pdf", FileMode.Create));
document.Open();
copy.AddPage(copy.GetImportedPage(reader, i));
document.Close();
}
}
Upvotes: 1
Views: 1937
Reputation: 433
I am using this code here now. Works fine and is more easy.
FileInfo file = new FileInfo(textBox2.Text);
using (PdfReader reader = new PdfReader(textBox2.Text))
{
for (int pagenumber = 1; pagenumber <= reader.NumberOfPages; pagenumber++)
{
string filename = System.IO.Path.GetFileNameWithoutExtension(file.Name);
Document document = new Document();
if(PdfTextExtractor.GetTextFromPage(reader, pagenumber, new SimpleTextExtractionStrategy()).Contains("LoremIpsum"))
{
PdfCopy copy = new PdfCopy(document, new FileStream(textBox3.Text + "\\" + filename + pagenumber + ".pdf", FileMode.Create));
document.Open();
copy.AddPage(copy.GetImportedPage(reader, pagenumber));
document.Close();
}
}
}
Upvotes: 0
Reputation: 9012
I would use following code:
public static List<Integer> determineSplits(String fileName) throws FileNotFoundException, IOException
{
PdfDocument pdfDocument = new PdfDocument(new PdfReader(fileName));
List<Integer> splitPages = new ArrayList<>();
for(int i=1;i<=pdfDocument.getNumberOfPages();i++) {
String pageTxt = PdfTextExtractor.getTextFromPage(pdfDocument.getPage(i));
if(pageTxt.contains("LoremIpsum"))
{
splitPages.add(1);
}
}
pdfDocument.close();
}
This generates a list of pages that need to be included. Then you can use iText code to separate out the pages you want using
public List<PdfPage> PdfDocument::copyPagesTo(int pageFrom,
int pageTo,
PdfDocument toDocument,
IPdfPageExtraCopier copier)
Upvotes: 6