Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

c# - iTextSharp how to rotate/switch page from landscape to portrait

I'm using iTextSharp to merge multiple PDF files into a single Pdf. I found a code sample or two on the web as to how to accomplish this task.

They all work, with no apparent issues, as I'm able to merge multiple PDF files into a single PDF.

The issue that I do have is that I would like for all the pages to be in PORTRAIT, as some of the PDF files have pages in LANDSCAPE and I would like for them to be rotated to PORTRAIT. I do not mind that they will either be upside down or sideways, but they must all be in portrait.

Looking at the code sections in the examples listed:

page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);

always returns the page rotation value as 0 (zero) thus the code section

if (rotation == 90 rotation == 270)
{
    cb.AddTemplate(page, 0, -1f, 1f, 0, 0, 
                         reader.GetPageSizeWithRotation(i).Height);
}

never gets executed (if that is what is supposed to do, rotating the page).

So, based on the code in the link of the 1st code sample page = writer.GetImportedPage(reader, i) how would I go about to change the page layout of the page from Landscape to Portrait, before I add it to the new merged PDF document with cb.AddTemplate...?

PS. Determining whether a page is either landscape or portrait I use the following piece of code obtained from SO (adapted for the code example above):

float pageXYRatio = page.Width / page.Height;
if (XYRatio > 1f)
{
    //page is landscape
}
else
{
    //page is portrait
}

Any help would be appreciated.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I used something like this.

cb.PdfDocument.NewPage();
PdfImportedPage page1 = writer.GetImportedPage(reader, i);

Rectangle psize = reader.GetPageSizeWithRotation(i);
switch (psize.Rotation)
{
    case 0:
        cb.AddTemplate(page1, 1f, 0, 0, 1f, 0, 0);
        break;
    case 90:
        cb.AddTemplate(page1, 0, -1f, 1f, 0, 0, psize.Height);
        break;
    case 180:
        cb.AddTemplate(page1, -1f, 0, 0, -1f, 0, 0);
        break;
    case 270:
        cb.AddTemplate(page1, 0, 1.0F, -1.0F, 0, psize.Width, 0);
        break;
    default:
        break;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...