使用iTextsharp将PDF拆分为多个PDF [英] Split PDF into multiple PDFs using iTextsharp
问题描述
public int SplitAndSave(string inputPath, string outputPath)
{
FileInfo file = new FileInfo(inputPath);
string name = file.Name.Substring(0, file.Name.LastIndexOf("."));
using (PdfReader reader = new PdfReader(inputPath))
{
for (int pagenumber = 1; pagenumber <= reader.NumberOfPages; pagenumber++)
{
string filename = pagenumber.ToString() + ".pdf";
Document document = new Document();
PdfCopy copy = new PdfCopy(document, new FileStream(outputPath + "\\" + filename, FileMode.Create));
document.Open();
copy.AddPage(copy.GetImportedPage(reader, pagenumber));
document.Close();
}
return reader.NumberOfPages;
}
}
我想拆分Pdf in到50页间隔的多个PDF。(如果有400页PDF,我想要8个pdf)。上面的代码将每个页面拆分为pdf。请帮帮我...我正在使用带有iTextSharp的asp.net。
I want to split the Pdf in to multiple PDFs with 50 pages interval.(Suppoose If there are 400 pages PDF, I want 8 pdfs). The above code is splitting every page into a pdf. Please help me...I'm using asp.net with iTextSharp.
推荐答案
你正在循环使用pdf并创建每次推进页面时都会出现一个新文档。您需要跟踪您的页面,以便每50页执行一次拆分。我个人会把它放在一个单独的方法中,并从你的循环中调用它。这样的事情:
You're looping through the pdf and creating a new document every time you advance a page. You'll need to keep track of your pages so that you perform split only every 50 pages. Personally I would put that in a separate method and call it from your loop. Something like this:
private void ExtractPages(string sourcePDFpath, string outputPDFpath, int startpage, int endpage)
{
PdfReader reader = null;
Document sourceDocument = null;
PdfCopy pdfCopyProvider = null;
PdfImportedPage importedPage = null;
reader = new PdfReader(sourcePDFpath);
sourceDocument = new Document(reader.GetPageSizeWithRotation(startpage));
pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(outputPDFpath, System.IO.FileMode.Create));
sourceDocument.Open();
for (int i = startpage; i <= endpage; i++)
{
importedPage = pdfCopyProvider.GetImportedPage(reader, i);
pdfCopyProvider.AddPage(importedPage);
}
sourceDocument.Close();
reader.Close();
}
因此,在原始代码循环中通过pdf并且每50页调用以上内容方法。您只需在块中添加变量即可跟踪开始/结束页面。
So in your original code loop through your pdf and every 50 pages call the above method. You'll just need to add variables in your block to keep track of the start/end pages.
这篇关于使用iTextsharp将PDF拆分为多个PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!