1.引用iTextSharp,用于拆分和合并pdf文件
using iTextSharp.text; using iTextSharp.text.pdf;
2.合并pdf
1 2 //outMergeFile是pdf文件合并后的输出路径 3 //lstFile里存放要进行合并的pdf文件的路径 4 public static void mergePDFFiles(string outMergeFile, List<string> lstFile) 5 { 6 7 if (!Sql.IsEmptyString(outMergeFile)) 8 { 9 try 10 { 11 PdfReader reader; 12 Document document = new Document(); 13 PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Server.MapPath(outMergeFile), FileMode.Create)); 14 document.Open(); 15 PdfContentByte cb = writer.DirectContent; 16 PdfImportedPage newPage; 17 for (int i = 0; i < lstFile.Count; i++) 18 { 19 string newpath = lstFile[i]; 20 reader = new PdfReader(newpath); 21 int iPageNum = reader.NumberOfPages; 22 int startPage = 1; 23 int rotation; 24 while (startPage <= iPageNum) 25 { 26 document.SetPageSize(reader.GetPageSizeWithRotation(startPage)); 27 document.NewPage(); 28 newPage = writer.GetImportedPage(reader, startPage); 29 rotation = reader.GetPageRotation(startPage);//获取每一页pdf文件的rotation
//根据每一页的rotation重置宽高,否则都按首页宽高合并可能会造成信息丢失 30 if (rotation == 90) 31 { 32 cb.AddTemplate(newPage, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(startPage).Height); 33 } 34 else if (rotation == 180) 35 { 36 cb.AddTemplate(newPage, -1f, 0, 0, -1f, reader.GetPageSizeWithRotation(startPage).Width, reader.GetPageSizeWithRotation(startPage).Height); 37 } 38 else if (rotation == 270) 39 { 40 cb.AddTemplate(newPage, 0, 1f, -1f, 0, reader.GetPageSizeWithRotation(startPage).Width, 0); 41 } 42 else 43 { 44 cb.AddTemplate(newPage, 1f, 0, 0, 1f, 0, 0); 45 } 46 startPage++; 47 } 48 } 49 document.Close(); 50 } 51 catch (Exception ex) 52 { 53 outMergeFile = string.Empty; 54 SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex); 55 } 56 } 57 }
3.pdf拆分
1
注: 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) 2 { 3 PdfReader reader = new PdfReader(imageCONTENT); 4 FileStream outFileStream = new FileStream(sImagePath, FileMode.Create); 5 Document destinationDoc = null; 6 PdfCopy pdfCopy = null; 7 destinationDoc = new Document(); 8 pdfCopy = new PdfCopy(destinationDoc, outFileStream); 9 destinationDoc.Open(); 10 if (list.Count > 0) 11 { 12 int pageArrayIndex = 0; 13 while (pageArrayIndex < list.Count) 14 { 15 destinationDoc.SetPageSize(reader.GetPageSizeWithRotation(list[pageArrayIndex])); 16 destinationDoc.NewPage(); 17 pdfCopy.AddPage(pdfCopy.GetImportedPage(reader, list[pageArrayIndex])); 18 pageArrayIndex++; 19 } 20 } 21 destinationDoc.Close(); 22 destinationDoc.Dispose(); 23 destinationDoc = null; 24 }