【发布时间】:2011-05-27 03:12:52
【问题描述】:
我正在尝试将 iTextSharp 集成到现有的文档成像应用程序中,该应用程序允许用户旋转可能以不正确的角度扫描的单个页面(这种情况比我想象的更频繁)。
我的实际页面数据正确旋转了 90/180 度,但页面方向没有随之旋转。我刚刚开始使用 iTextSharp,所以我对它的方法还有些陌生,但能够使用 StackOverflow 的帖子拼凑出我迄今为止所拥有的东西。它很近,但不完全在那里。
这是我目前所拥有的:
' Get the input document and total number of pages
Dim inputPdf As New iTextSharp.text.pdf.PdfReader(fileName)
Dim pageCount As Integer = inputPdf.NumberOfPages
' Load the input document
Dim inputDoc As New iTextSharp.text.Document(inputPdf.GetPageSizeWithRotation(1))
' Set up the file stream for our output document
Dim outFileName As String = Path.ChangeExtension(fileName, "pdf")
Using fs As New FileStream(outFileName, FileMode.Create)
' Create the output writer
Dim outputWriter As iTextSharp.text.pdf.PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(inputDoc, fs)
inputDoc.Open()
' Copy pages from input to output document
Dim cb As iTextSharp.text.pdf.PdfContentByte = outputWriter.DirectContent
For index As Integer = 1 To pageCount
inputDoc.SetPageSize(inputPdf.GetPageSizeWithRotation(index))
inputDoc.NewPage()
' If this is our page to be rotated, perform the desired transform
' TODO - 90 degree rotations need to change the page orientation as well
Dim page As iTextSharp.text.pdf.PdfImportedPage = outputWriter.GetImportedPage(inputPdf, index)
If index = pageNum Then
Select Case angle
Case 90
cb.AddTemplate(page, 0, -1, 1, 0, 0, page.Height)
Case 180
cb.AddTemplate(page, -1, 0, 0, -1, page.Width, page.Height)
Case 270
cb.AddTemplate(page, 0, 1, -1, 0, page.Width, 0)
Case Else
' Should not be here, but don't do anything
cb.AddTemplate(page, 1, 0, 0, 1, 0, 0)
End Select
Else
' No rotation; add as is
cb.AddTemplate(page, 1, 0, 0, 1, 0, 0)
End If
Next
inputDoc.Close()
End Using
我尝试将以下代码添加到顶部以从现有页面中获取页面大小并在旋转角度为 90 或 270 时交换尺寸:
For index As Integer = 1 To pageCount
Dim pageSize As iTextSharp.text.Rectangle = inputPdf.GetPageSizeWithRotation(index)
If angle = 90 OrElse angle = 270 Then
' For 90-degree rotations, change the orientation of the page, too
pageSize = New iTextSharp.text.Rectangle(pageSize.Height, pageSize.Width)
End If
inputDoc.SetPageSize(pageSize)
inputDoc.NewPage()
不幸的是,这会导致 每个 页面旋转 90 度,而我想要旋转的页面上的数据无论如何都没有显示在正确的位置(它被向下移动并离开稍微翻页)。
就像我说的,我并不真正熟悉 API 的内部工作原理。我已经在 sourceforge 页面上在线查看了示例,并查看了这本书(两个版本),但我没有看到任何符合要求的内容。我在这里看到了一个示例,它显示了新编写的 PDF 的页面方向,但没有显示现有 PDF 的页面方向。有人可以帮帮我吗?谢谢!
【问题讨论】: