如何在C#中使用itextsharp库来识别pdf方向是否使用itextsharp库的横向或纵向?

问题描述:

任何人都可以知道如何使用C#中的itextsharp库识别pdf方向是横向还是纵向。如何在C#中使用itextsharp库来识别pdf方向是否使用itextsharp库的横向或纵向?

这是我的代码如下,它是检索PDF流和旋转图像,但我的问题是,我们如何识别方向?

public static string ReadPdfFile(string fileName) 
     { 
     StringBuilder text = new StringBuilder(); 

     if (File.Exists(fileName)) 
     { 




      byte[] bytes = System.IO.File.ReadAllBytes(fileName); 



      using (MemoryStream ms = new MemoryStream()) 
      { 
       Document doc = new Document(); 
       PdfWriter writer = PdfWriter.GetInstance(doc, ms); 
       doc.Open(); 
       PdfContentByte cb = writer.DirectContent; 
       PdfImportedPage page; 
       PdfReader reader; 
       reader = new PdfReader(bytes); 
       int pages = reader.NumberOfPages; 

       // loop over document pages 
       for (int i = 1; i <= pages; i++) 
       { 

        page = writer.GetImportedPage(reader, i); 
        //Rectangle pagesize = reader.GetPageSizeWithRotation(0); 
        AffineTransform scale = new AffineTransform(0, 1.0F, -1.0F, 0, 500, 500); 
        cb.AddTemplate(page,scale); 
       } 

       doc.Close(); 
       var rotatedFile = ms.GetBuffer(); 

       ms.Flush(); 
       ms.Dispose(); 
       string filepath = @"D:\test2.pdf"; 
       File.Delete(filepath); 
       using (FileStream Writer = new System.IO.FileStream(filepath, FileMode.Create, FileAccess.Write)) 
       { 
        Writer.Write(rotatedFile, 0, rotatedFile.Length); 
        string actualFilePath = "test2.pdf"; 
        filepath = actualFilePath; 
       } 


      } 

请帮助我,在此先感谢!

我评估一个页面的矩形大小以找出。需要注意的是......您可以在同一个文件中拥有多个方向,因此您无法仅基于第一页决定文件是否为横向。如果所有页面均为横向,则文件为横向,否则为混合方向文件。

Rectangle currentPageRectangle = pdfReader.GetPageSizeWithRotation(<PageNumberHere>); 
if (currentPageRectangle.Width > currentPageRectangle.Height) 
{ 
    //page is landscape 
} 
else 
{ 
    //page is portrait 
} 
+0

谢谢,你有什么想法的规模?如果pdf是肖像,那么我们执行 'AffineTransform scale = new AffineTransform(0,1.0F,-1.0F,0,500,500); cb.AddTemplate(page,scale);' 否则在景观检查我不想给任何规模,所以我想默认规模如何给予默认规模? –

+0

对不起,我不知道规模。 –