Burst.cs–split a PDF in several separate PDF files (1 per page)
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace chapter01
{
///
/// This example was written by Steven Lee.
/// http://blog.rubypdf.com
/// This tool lets you split a PDF in several separate PDF files (1 per page).
///
public class Burst
{
///
/// split a PDF in several separate PDF files (1 per page)
///
public static void Main(string[] args)
{
try
{
FileInfo file=new FileInfo(args[0]);
string name =file.Name.Substring(0,file.Name.LastIndexOf("."));
// we create a reader for a certain document
PdfReader reader = new PdfReader(args[0]);
// we retrieve the total number of pages
int n=reader.NumberOfPages;
int digits = 1 + (n / 10);
System.Console.WriteLine("There are " + n + " pages in the original file.");
Document document;
int pagenumber;
string filename;
for (int i = 0; i < n; i++)
{
pagenumber = i + 1;
filename =pagenumber.ToString();
while (filename.Length< digits) filename = "0" + filename;
filename = "_" + filename + ".pdf";
// step 1: creation of a document-object
document = new Document(reader.GetPageSizeWithRotation(pagenumber));
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(name+filename,FileMode.Create));
// step 3: we open the document
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page = writer.GetImportedPage(reader, pagenumber);
int rotation = reader.GetPageRotation(pagenumber);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pagenumber).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
// step 5: we close the document
document.Close();
}
}
catch (DocumentException de)
{
System.Console.Error.WriteLine(de.Message);
}
catch (IOException ioe)
{
System.Console.Error.WriteLine(ioe.Message);
}
}
}
}
This entry was posted
on Wednesday, October 11th, 2006 at 11:39 am and is filed under .NET, English, PDF, iText in Action, iTextSharp(iText#).
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.
October 11th, 2006 11:41
[...] Because this example need java version iText tools, so we need write a C# version Burst. [...]
October 11th, 2006 12:06
[...] 2006-10-11:Burst.cs–split a PDF in several separate PDF files (1 per page) « 临安特产--无核方柿 | HelloWorld–C# version examples of iText in Action » [...]
January 27th, 2011 17:41
Dear Team,
I can split the PDF successfully with your code. At the same time, i findone issue. If the Main PDF file contains any links(Hyperlink to new site), the splitted PDF does not the have the hyperlink. Hyerlinks are removed in the splitted PDF.
I want to stay the hyperlink in the pdf also.
Please help me to resolver this error.