using iTextSharp.text;
using iTextSharp.text.pdf;
/// <summary>
/// 合併PDF
/// </summary>
/// <param name="fileList">被合併的文件集合</param>
/// <param name="outMergeFile">合併文件路徑</param>
/// <param name="iFlag">0:A4直印, 1:A4橫印</param>
public void MergePDFFiles(string[] fileList, string outMergeFile, int iFlag)
{
PdfReader reader;
Document document = new Document();
if (iFlag != 0)
{
document = new Document(iTextSharp.text.PageSize.A4.Rotate());
}
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage newPage;
for (int i = 0; i < fileList.Length; i++)
{
if (fileList[i] != null && fileList[i] != string.Empty)
{
reader = new PdfReader(fileList[i]);
int iPageNum = reader.NumberOfPages;
for (int j = 1; j <= iPageNum; j++)
{
document.NewPage();
newPage = writer.GetImportedPage(reader, j);
cb.AddTemplate(newPage, 0, 0);
}
}
}
document.Close();
}
/// <summary>
/// 合併PDF 自動判斷方向
/// </summary>
/// <param name="fileList">被合併的文件集合</param>
/// <param name="outMergeFile">合併文件路徑</param>
public void MergePDFFiles(string[] fileList, string outMergeFile)
{
int f = 0;
PdfReader reader = new PdfReader(fileList[f]);
Document document = new Document();
document = new Document(reader.GetPageSizeWithRotation(1));
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage newPage;
int rotation = 0;
for (int i = 0; i < fileList.Length; i++)
{
if (fileList[i] != null)
{
reader = new PdfReader(fileList[i]);
int iPageNum = reader.NumberOfPages;
for (int j = 1; j <= iPageNum; j++)
{
document.NewPage();
newPage = writer.GetImportedPage(reader, j);
rotation = reader.GetPageRotation(j);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(newPage, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(newPage, 1f, 0, 0, 1f, 0, 0);
}
}
}
}
}
感謝您的分享,合併PDF 自動判斷方向 少了 document.Close();
回覆刪除