当前位置: 首页 > 编程语言 > C#

使用iTextSharp在C#中旋转PDF分享

时间:2023-04-10 14:50:43 C#

C#学习教程:在C#中使用iTextSharp旋转PDF虽然它正在拆分PDF,但内容倒置显示。如何将其旋转180度。请帮忙。下面是相同的代码privatestaticvoidExtractPages(stringinputFile,stringoutputFile,intstart,intend){//获取输入文档PdfReaderinputPdf=newPdfReader(inputFile);//检索总页数intpageCount=inputPdf.NumberOfPages;如果(结束页数){结束=页数;}//加载输入文档DocumentinputDoc=newDocument(inputPdf.GetPageSizeWithRotation(1));//使用(FileStreamfs=newFileStream(outputFile,FileMode.Create))创建文件流{//创建输出编写器PdfWriteroutputWriter=PdfWriter.GetInstance(inputDoc,fs);inputDoc.Open();PdfContentBytecb1=outputWriter.DirectContent;//将页面从输入文档复制到输出文档for(inti=start;i<=end;i++){inputDoc.SetPageSize(inputPdf.GetPageSizeWithRotation(1));inputDoc.NewPage();PdfImportedPagepage=outputWriter.GetImportedPage(inputPdf,i);introtation=inputPdf.GetPageRotation(i);如果(旋转==90||旋转==270){cb1.Add模板(页面,0,-1f,1f,0,0,inputPdf.GetPageSizeWithRotation(i)。高度);}else{cb1.AddTemplate(page,1f,0,0,1f,0,0);}}inputDoc.Close();我试过你的代码,它对我来说很好用;拆分页面保持其原始方向解决方法可能是明确地将页面旋转180度。替换:cb1.AddTemplate(page,1f,0,0,1f,0,0);附加:cb1.AddTemplate(page,-1f,0,0,-1f,inputPdf.GetPageSizeWithRotation(i).Width,inputPdf.GetPageSizeWithRotation(i).Height);如果您对inputPdf.GetPageRotation(i)的调用返回180,那么您可以在inputPdf.GetPageRotation(i)的if语句中处理它(使用我建议的旋转代码==180)。我发现上面的答案没有正确旋转所有4个主要旋转。下面是我正确处理0,90,180和270的代码。测试了以这些方向旋转的PDF。varpageRotation=reader.GetPageRotation(currentPageIndex);varpageWidth=reader.GetPageSizeWithRotation(currentPageIndex).Width;varpageHeight=reader.GetPageSizeWithRotation(currentPageIndex).Height;switch(pageRotation){案例0:writer.DirectContent.AddTemplate(importedPage,1f,0,0,1f,0,0);休息;案例90:writer.DirectContent.AddTemplate(importedPage,0,-1f,1f,0,0,pageHeight);休息;案例180:writer.DirectContent.AddTemplate(importedPage,-1f,0,0,-1f,pageWidth,pageHeight);休息;案例270:writer.DirectContent.AddTemplate(importedPage,0,1f,-1f,0,pageWidth,0);休息;默认值:抛出新的InvalidOperationException(string.Format(“意外的页面旋转:[{0}]。”,pageRotation));}你应该试试这个。它对我有用:if(rotation==90||rotation==270){if(rotation==90){cb.AddTemplate(page,0,-1f,1f,0,0,reader.GetPageSizeWithRotation(pagenumber)。高度);}if(rotation==270){cb.AddTemplate(page,0,1.0F,-1.0F,0,reader.GetPageSizeWithRotation(pagenumber).Width,0);}}else{cb.AddTemplate(page,1f,0,0,1f,0,0);@TimS的答案非常接近完美,并为AddTemplate提供了正确的参数,但我需要做一些添加以允许旋转PDF的AddTemplate,其中页面已经旋转AddTemplate或270:假设RotateFlipType参数RotateFlipTyperotateFlipType传递给指定旋转的函数(来自GDI+RotateFlip调用的便捷枚举):iTextSharp.text.pdf.PdfContentBytecb=writer.DirectContent;iTextSharp.text.pdf.PdfImportedPage页面;内部旋转;诠释我=0;同时(我希望这会帮助其他人纠正传入的PDF文件的旋转。我花了2天时间来完善它。上面的旧代码对案例270进行了轻微更改:writer.DirectContent.AddTemplate(importedPage,0,1f,-1f,0,pageWidth,0);新代码案例270:writer.DirectContent.AddTemplate(importedPage,0,1f,-1f,0,pageHeight,0);这样就解决了270度旋转的问题以上是C#学习教程:C#中使用iTextSharp旋转PDF分享全部内容,如果对大家有用需要进一步了解C#学习教程,希望大家会多加关注---本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: