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);
			}
		}
	}
}
Share and Enjoy:
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • BlinkList
  • blogmarks
  • blogtercimlap
  • connotea
  • DotNetKicks
  • Fark
  • Fleck
  • Gwar
  • Haohao
  • IndianPad
  • Internetmedia
  • LinkaGoGo
  • MyShare
  • Netscape
  • NewsVine
  • Rec6
  • Reddit
  • Scoopeo
  • Slashdot
  • StumbleUpon
  • Technorati
  • Webride

3 Responses to “Burst.cs–split a PDF in several separate PDF files (1 per page)

Leave a Reply

You must be logged in to post a comment.