Developer Tools
|
Office Productivity Applications
|
Enterprise Solutions
|
|||||||||||||||||||||||||||
In this article, we will see how to rearrange pages in an existing PDF document. For an example, we will use a document with say 10 pages. We will try to move page 2 to the position of page 5.
First, we use the ExtractPagesTo() method of TgtPDFDocument class to extract Page 2. Next, we delete Page 2 from the document using DeletePages() method. Finally, we copy the extracted page from the temporary document to location of Page 5 in the original document using the method InsertPagesFrom().
var LFrom: String; LToPage: Integer; LTempDoc, PDFDoc: TgtPDFDocument; Lstream:TMemoryStream; begin try PDFDoc := TgtPDFDocument.Create(Nil); // Load input PDF document PDFDoc.LoadFromFile('Input.pdf'); // Disable interactivity PDFDoc.ShowSetupDialog := False; PDFDoc.OpenAfterSave := False; // Create a memory stream Lstream :=TMemoryStream.Create; // Create a temporary PDF document object LTempDoc := TgtPDFDocument.Create(self); LTempDoc.ShowSetupDialog := False; LTempDoc.OpenAfterSave := False; // Page position from a page // needs to be moved LFrom := '2'; // Page position to which a page // needs to moved LToPage := 5; if LToPage <= PDFDoc.PageCount then begin // Extract page 1 // to a temporary document PDFDoc.ExtractPagesTo(LTempDoc,LFrom); // Save extracted page to a memory stream LTempDoc.SaveToStream(Lstream); // Delete extracted page from input // PDF document PDFDoc.DeletePages(LFrom); // Load the temporary PDF document LTempDoc.LoadFromStream(Lstream); // Insert the extracted page (currently // page 1 in the temporary document) at // position page 5 PDFDoc.InsertPagesFrom(LTempDoc,'1',LToPage-1); // Save modified document PDFDoc.SaveToFile('Output.pdf'); end else ShowMessage('Page out of range ! Max Page = '+IntToStr(PDFDoc.PageCount)); finally LTempDoc.free; Lstream.Free; PDFDoc.Free; end;
You may have wondered why we are saving the temporary document object to a memory stream. When we call ExtractPagesTo(), it does retrieve Page 2 to the LTempDoc object, holding just a reference to that page but not yet representing the structure of a wholesome PDF document.
For this reason, we save it to a memory stream and load it again from that memory stream. When we do this, LTempDoc represents a wholesome independent PDF document with a very retrievable Page 1 (originally Page 2), which we can then insert at position of Page 5.
| Privacy | Legal | Feedback | Newsletter | © 2002-2009 Gnostice Information Technologies Private Limited. All rights reserved. |
This site is best viewed on a screen with minimum resolution of 1152 x 864 pixels. Windows users are advised to use Microsoft ClearType Tuning for optimal experience. Linux and other users can enable font smoothing, as supported by their OS. Also, please use the latest version of a standards-compliant browser such as Opera, FireFox, Chrome or Safari.