使用itextsharp重新排序pdf文件中的页面 [英] Reorder pages in a pdf file using itextsharp
问题描述
我正在尝试重新排序PDF文件中的多个页面。我在博客中发现了一些代码但无法使其工作。我有两页pdf,我想让最后一页显示为第一页。我总是得到一个例外,说页码必须与订单匹配。当我检查文档对象时,它显示0页。但传入的PDF有两页。
I'm trying to reorder several pages in a PDF file. I found some code in a blog but couldn't get it to work. I have a two page pdf, and I want to get the last page to appear as first. I always get an exception saying that page number has to match with order. When I checked the document object, it shows 0 pages. But the PDF passed into has two pages.
public void reOrder(string inputFile)
{
Document document = new Document();
FileStream fs = new FileStream(inputFile, FileMode.Open);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.AddDocListener(writer);
writer.SetLinearPageMode();
int[] order = {2,1};
writer.ReorderPages(order);
}
推荐答案
每当你用iTextSharp写的时候您需要创建新文档,它永远不会写入现有文档。在您的情况下,页面重新排序需要编写,因此您需要创建一个新文档,将页面重新排序然后重新排序。 (当然,你也可以在导入时重新排序它们。)
Whenever you use iTextSharp to write something you need to create a new document, it will never write to an existing document. In your case, page reordering would require writing so you need create a new document, bring over the pages and then reorder them. (Of course, you could also just reorder them upon import, too.)
var inputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
var output = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf");
//Bind a reader to our input file
var reader = new PdfReader(inputFile);
//Create our output file, nothing special here
using (FileStream fs = new FileStream(output, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (Document doc = new Document(reader.GetPageSizeWithRotation(1))) {
//Use a PdfCopy to duplicate each page
using (PdfCopy copy = new PdfCopy(doc, fs)) {
doc.Open();
copy.SetLinearPageMode();
for (int i = 1; i <= reader.NumberOfPages; i++) {
copy.AddPage(copy.GetImportedPage(reader, i));
}
//Reorder pages
copy.ReorderPages(new int[] { 2, 1 });
doc.Close();
}
}
}
这篇关于使用itextsharp重新排序pdf文件中的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!