How to apply rotations, scaling, and transformations on PDF pages?

34 views
Skip to first unread message

Ryan

unread,
Mar 7, 2017, 8:20:41 PM3/7/17
to PDFTron PDFNet SDK
Question:

We want to apply rotations, scaling, and transformations on PDF pages. How can we do that?

Answer:

Note, that there are helper functions for part of this.
Page.Scale
And translation could be done by modifying the Media and Crop boxes.

However, assuming you are comfortable with 2D matrices, the following code would be the easiest to understand and use.

The following code is how you could apply arbitrary transformations on a PDF page.

using (PDFDoc src_doc = new PDFDoc(@"input.pdf"))
using (PDFDoc dst_doc = new PDFDoc())
using (ElementBuilder builder = new ElementBuilder())
using (ElementWriter writer = new ElementWriter())
{
    src_doc
.InitSecurityHandler();

   
ArrayList copy_pages = new ArrayList();
    copy_pages
.Add(src_doc.GetPage(1));
   
ArrayList imported_pages = dst_doc.ImportPages(copy_pages);
   
Page src_page = imported_pages[0] as Page;

   
Page new_page = dst_doc.PageCreate(src_page.GetCropBox());
    writer
.Begin(new_page);
   
Element element = builder.CreateForm(src_page);

   
Matrix2D origin = new Matrix2D(1, 0, 0, 1, -src_page.GetPageWidth() / 2, -src_page.GetPageHeight() / 2);
   
Matrix2D scale = new Matrix2D(2, 0, 0, 2, 0, 0);
   
Matrix2D rot = Matrix2D.RotationMatrix(Math.PI / 2);
   
Matrix2D trans = new Matrix2D(1, 0, 0, 1, 300, 300);

    element
.GetGState().SetTransform(origin.Inverse() * trans * rot * scale * origin);

    writer
.WritePlacedElement(element);
    writer
.End();

    dst_doc
.PagePushBack(new_page);
    dst_doc
.Save(@"output.pdf", SDFDoc.SaveOptions.e_linearized | SDFDoc.SaveOptions.e_remove_unused);
}

Reply all
Reply to author
Forward
0 new messages