pdf拆分与合并

1.引用iTextSharp,用于拆分和合并pdf文件

using iTextSharp.text;
using iTextSharp.text.pdf;

2.合并pdf

 //outMergeFile是pdf文件合并后的输出路径
//lstFile里存放要进行合并的pdf文件的路径
public static void mergePDFFiles(string outMergeFile, List<string> lstFile)
{ if (!Sql.IsEmptyString(outMergeFile))
{
try
{
PdfReader reader;
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Server.MapPath(outMergeFile), FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage newPage;
for (int i = ; i < lstFile.Count; i++)
{
string newpath = lstFile[i];
reader = new PdfReader(newpath);
int iPageNum = reader.NumberOfPages;
int startPage = ;
int rotation;
while (startPage <= iPageNum)
{
document.SetPageSize(reader.GetPageSizeWithRotation(startPage));
document.NewPage();
newPage = writer.GetImportedPage(reader, startPage);
rotation = reader.GetPageRotation(startPage);//获取每一页pdf文件的rotation
                  //根据每一页的rotation重置宽高,否则都按首页宽高合并可能会造成信息丢失
if (rotation == )
{
cb.AddTemplate(newPage, , -1f, 1f, , , reader.GetPageSizeWithRotation(startPage).Height);
}
else if (rotation == )
{
cb.AddTemplate(newPage, -1f, , , -1f, reader.GetPageSizeWithRotation(startPage).Width, reader.GetPageSizeWithRotation(startPage).Height);
}
else if (rotation == )
{
cb.AddTemplate(newPage, , 1f, -1f, , reader.GetPageSizeWithRotation(startPage).Width, );
}
else
{
cb.AddTemplate(newPage, 1f, , , 1f, , );
}
startPage++;
}
}
document.Close();
}
catch (Exception ex)
{
outMergeFile = string.Empty;
SplendidError.SystemError(new StackTrace(true).GetFrame(), ex);
}
}
}

3.pdf拆分


注:              string[] sPages = sSplitText.Split(',');
List<int> list = new List<int>();
foreach (string val in sPages)
{
list.Add(Sql.ToInteger(val));
}
private void SplitPdf(byte[] imageCONTENT, string sImagePath, List<int> list)
{
PdfReader reader = new PdfReader(imageCONTENT);
FileStream outFileStream = new FileStream(sImagePath, FileMode.Create);
Document destinationDoc = null;
PdfCopy pdfCopy = null;
destinationDoc = new Document();
pdfCopy = new PdfCopy(destinationDoc, outFileStream);
destinationDoc.Open();
if (list.Count > )
{
int pageArrayIndex = ;
while (pageArrayIndex < list.Count)
{
destinationDoc.SetPageSize(reader.GetPageSizeWithRotation(list[pageArrayIndex]));
destinationDoc.NewPage();
pdfCopy.AddPage(pdfCopy.GetImportedPage(reader, list[pageArrayIndex]));
pageArrayIndex++;
}
}
destinationDoc.Close();
destinationDoc.Dispose();
destinationDoc = null;
}
上一篇:基于 abp vNext 和 .NET Core 开发博客项目 - 博客接口实战篇(四)


下一篇:在一个XAML中点击按钮,界面跳转到另一个XAML界面方法