PAYATHON 2026

iText7 合并多个 PDF 时 PdfWriter 报 Unknown PDFException

数据小陈

结论

Unknown PDFException 出现在 PdfWriter 构造函数这一行,通常说明 iText 在打开输出文件或初始化写入流时失败了,只是底层异常没有被映射成更具体的 PdfException。在改 PdfMerger 的调用之前,先抓取完整异常和 InnerException,再检查输出路径、写入权限、文件占用和 NuGet 依赖。

先拿到真实异常

把 ex.Message 换成 ex.ToString(),同时把 ex.InnerException 也输出。只看到 Unknown PDFException 时,这些信息往往不够定位问题。

Catch ex As Exception
    Console.WriteLine(ex.ToString())
    If ex.InnerException IsNot Nothing Then
        Console.WriteLine("InnerException: " & ex.InnerException.ToString())
    End If
End Try

常见原因与处理

  1. 输出目录不存在,或者当前进程没有写权限。先确认 C:\PDFs 存在,并给运行程序使用的账号授予写权限。
  2. 输出文件被 Adobe Acrobat、预览器、杀毒软件或其他进程占用,或者文件本身是只读的。关掉占用它的程序,删除或重命名旧输出文件后再试。
  3. 输出文件和某个输入文件是同一个,导致同一个 PDF 被同时读写。输出文件要单独命名,不能和输入文件重名。
  4. 项目依赖不完整。建议用 NuGet 安装并还原 itext7,清理并重新生成;如果是手工引用 DLL,还要确认相关依赖程序集已经复制到运行目录。某些版本或功能需要对应的 BouncyCastle 适配包,具体看实际包依赖。
  5. 路径过长、特殊字符、网络盘或权限受限目录也可能让异常被包装后抛出。可以先把输出改到 Path.GetTempPath() 下验证。

可直接运行的示例

下面的代码用 FileStream 显式创建输出文件,并提前检查目录和输入/输出冲突:

Imports System
Imports System.IO
Imports iText.Kernel.Pdf
Imports iText.Kernel.Utils

Module Program
    Sub Main()
        Dim inputFiles As String() = {
            "C:\PDFs\file1.pdf",
            "C:\PDFs\file2.pdf",
            "C:\PDFs\file3.pdf"
        }

        Dim outputFile As String = "C:\PDFs\MergedOutput.pdf"

        Try
            If inputFiles.Length = 0 Then
                Console.WriteLine("No input files specified.")
                Return
            End If

            For Each filePath In inputFiles
                If Not File.Exists(filePath) Then
                    Console.WriteLine($"Error: File not found - {filePath}")
                    Return
                End If
            Next

            Dim outputDir = Path.GetDirectoryName(outputFile)
            If Not String.IsNullOrWhiteSpace(outputDir) Then
                Directory.CreateDirectory(outputDir)
            End If

            For Each filePath In inputFiles
                If String.Equals(Path.GetFullPath(filePath), Path.GetFullPath(outputFile), StringComparison.OrdinalIgnoreCase) Then
                    Throw New InvalidOperationException("输出文件不能与输入文件相同:" & outputFile)
                End If
            Next

            Using outputStream As New FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)
                Using pdfWriter As New PdfWriter(outputStream)
                    Using pdfDoc As New PdfDocument(pdfWriter)
                        Dim merger As New PdfMerger(pdfDoc)

                        For Each filePath In inputFiles
                            Using reader As New PdfReader(filePath)
                                Using srcDoc As New PdfDocument(reader)
                                    merger.Merge(srcDoc, 1, srcDoc.GetNumberOfPages())
                                End Using
                            End Using
                        Next
                    End Using
                End Using
            End Using

            Console.WriteLine($"PDFs merged successfully into: {outputFile}")
        Catch ex As Exception
            Console.WriteLine("An error occurred while merging PDFs: " & ex.ToString())
            If ex.InnerException IsNot Nothing Then
                Console.WriteLine("InnerException: " & ex.InnerException.ToString())
            End If
        End Try
    End Sub
End Module

注意事项

  • 合并时让输入文档以只读方式打开,输出文档单独创建,不要在同一个 PdfDocument 上同时读写。
  • 如果部署在 IIS 或 Windows 服务中,不要只检查当前登录用户的权限,还要确认应用池账号对输出目录有写权限。
  • 清理 NuGet 缓存并重新还原依赖后仍然报错,保留完整堆栈和 InnerException 信息再继续排查。

备注:内容仅供参考。