用其中一个就行,第一个测试正常

第一个试了完美
//合并多个PDF
public static void MergePdfFiles(string outputFilePath, params string[] inputFilePaths)
{
    try
    {
        inputFilePaths = inputFilePaths.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();   //先去掉空值 
        // 创建一个新的PDF文档用于合并
        PdfSharp.Pdf.PdfDocument outputDocument = new PdfSharp.Pdf.PdfDocument();

        foreach (string inputFile in inputFilePaths)
        {
            // 加载要合并的PDF
            PdfSharp.Pdf.PdfDocument inputDocument = PdfSharp.Pdf.IO.PdfReader.Open(inputFile, PdfDocumentOpenMode.Import);

            // 将每个PDF的页面添加到输出文档中
            for (int pageIndex = 0; pageIndex < inputDocument.PageCount; pageIndex++)
            {
                PdfSharp.Pdf.PdfPage page = inputDocument.Pages[pageIndex];
                outputDocument.AddPage(page);
            }

            // 关闭输入文档
            //inputDocument.Close();
        }

        // 保存合并后的PDF文件
        outputDocument.Save(outputFilePath);
        outputDocument.Close();
    }
    catch (Exception ex)
    {

        throw new Exception(ex.Message);
    }

}

//这个试了不能铺满,不知什么原因
// 合并多个PDF
/// <param name="SourcePath">源路径</param>
/// <param name="TargetPath">目标路径</param>
/// <param name="NewFileName">新文件名</param>
public static void MergePDF(string SourcePath, string outputFilePath)
{
    //需要合并的pdf集合
    string[] fileList = Directory.GetFiles(SourcePath, "*.pdf", SearchOption.AllDirectories);
    //合并到的总PDF
    iTextSharp.text.pdf.PdfReader reader;
    iTextSharp.text.Document document = new iTextSharp.text.Document();
    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFilePath, FileMode.Create));
    document.Open();
    PdfContentByte cb = writer.DirectContent;
    PdfImportedPage newPage;
    for (int i = 0; i < fileList.Length; i++)
    {
        reader = new iTextSharp.text.pdf.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();
}

 

https://www.88531.cn/?p=30112

www.npspro.cn软师兄
软师兄 » C#合并多个PDF文件,把多个文件合成一个两个函数
50T免费网盘资源大集合【持续更中~~~~】:点击查看