Moussawi
Moussawi

Reputation: 403

Split PDF page to multiple page in C#

I'm creating an application for Windows 8.1 in C#. Into Windows.Data.Pdf i've found how use PDF files in my application. But i want to know if i can split one A3 page to multiple PDF files ?

Upvotes: 0

Views: 2655

Answers (1)

Bruno Lowagie
Bruno Lowagie

Reputation: 77528

You don't want to split a page, you want to tile it.

This is explained in Chapter 6 of my book (section 6.2.3). Take a look at the TilingHero example (Java / C#). In this example, one large page (hero.pdf) is split into a PDF with several A4 pages (superman.pdf).

enter image description here

This is some code:

PdfReader reader = new PdfReader(resource);
Rectangle pagesize = reader.GetPageSizeWithRotation(1); 
using (Document document = new Document(pagesize)) {
    // step 2
    PdfWriter writer = PdfWriter.GetInstance(document, ms);
    // step 3
    document.Open();
    // step 4
    PdfContentByte content = writer.DirectContent;
    PdfImportedPage page = writer.GetImportedPage(reader, 1);
    // adding the same page 16 times with a different offset
    float x, y;
    for (int i = 0; i < 16; i++) {
        x = -pagesize.Width * (i % 4);
        y = pagesize.Height * (i / 4 - 3);
        content.AddTemplate(page, 4, 0, 0, 4, x, y);
        document.NewPage();
     }
}

The math is valid for an A0 page. You need to adapt it for an A3 page (meaning: the math you need is way easier to do).

You need to calculate pagesize so that it results in smaller pages, and then use something like this:

using (Document document = new Document(pagesize)) {
    // step 2
    PdfWriter writer = PdfWriter.GetInstance(document, ms);
    // step 3
    document.Open();
    // step 4
    PdfContentByte content = writer.DirectContent;
    PdfImportedPage page = writer.GetImportedPage(reader, 1);
    // adding the same page 16 times with a different offset
    float x, y;
    for (int i = 0; i < 16; i++) {
        x = -pagesize.Width * (i % 4);
        y = pagesize.Height * (i / 4 - 3);
        content.AddTemplate(page, x, y); // we don't scale anymore
        document.NewPage();
     }
}

Upvotes: 1

Related Questions