有没有办法使用 itext7 和 C# 获取 PdfDocument 对象的完整路径(甚至只是文件名)?

问题描述 投票:0回答:2

我有一个 PdfDocument 对象列表,这些对象是按页码从一个大型原始 PDF 文件中分割出来的(原始文件中的每一页都有一个文档)。

我想做的就是迭代这些文档

foreach (PdfDocument doc in splitDocuments)

并获取每个文件的文件路径/文档名称,但我无法找到为我提供基本信息的属性。我需要根据文件内的一些信息将文件复制到不同的位置,但到目前为止我还无法获取文件路径。

感谢您的帮助!

c# pdf itext7
2个回答
1
投票

一般来说,

PdfDocument
没有唯一的文件名。

首先请记住,

PdfDocument
可以基于
PdfReader
PdfWriter
PdfReader
/
PdfWriter
对创建。读取器和写入器都可以是基于文件的。因此,一般来说,不清楚“该”文件名的含义,可能有两个。但两者也可能都是基于非文件对象,那就没有文件名了。

如果

PdfWriter
是基于文件的,您可以从底层
FileStream
确定关联的文件名,对于
PdfDocument doc

doc.GetWriter().GetOutputStream()

对于

PdfReader
来说,等效操作并不容易(如果可能的话):根据使用的选项,文件可能已被读入字节数组,然后被遗忘。但即使如此,即如果阅读器仍然基于文件流,它也隐藏在两层或三层
internal
private
信息之下。使用反射,您可以处理这些层,但这当然不适合生产目的。

您还提到那些

PdfDocument
对象是从一个大的原始PDF中分割出来的。如果这是通过
PdfSplitter
实用程序类实现的,那么这些文档就没有
PdfReader
开头。


0
投票

以下方法将按照给定的页数拆分文件并返回所有新文件的名称。它使用 itext7 库。

        public class PdfHelper
        {
            public List<String> SplitPDF(string sourcePDFpath, int pageCount)
            {
                FileInfo info = new FileInfo(sourcePDFpath);
                string nameWithoutExtension = Path.GetFileNameWithoutExtension(sourcePDFpath);

                PdfDocument pdfDoc = new PdfDocument(new PdfReader(sourcePDFpath));
                PdfSplitterWithFileNames splitter = new PdfSplitterWithFileNames(pdfDoc, info.DirectoryName, nameWithoutExtension);

                IList<PdfDocument> splitDocuments = splitter.SplitByPageCount(pageCount);

                foreach (PdfDocument doc in splitDocuments)
                {
                    doc.Close();
                }
                pdfDoc.Close();

                return splitter.SplitFileNames;
            }

            private class PdfSplitterWithFileNames : PdfSplitter
            {
                private String destFolder;
                private String fileName;
                private int partNumber = 1;

                public List<string> SplitFileNames { get; set; }

                public PdfSplitterWithFileNames(PdfDocument pdfDocument, String destinationFolder, string splitFileName) : base(pdfDocument)
                {
                    this.destFolder = destinationFolder;
                    this.fileName = splitFileName;
                    SplitFileNames = new List<string>();
                }

                protected override PdfWriter GetNextPdfWriter(PageRange documentPageRange)
                {
                    string newFileName = $@"{destFolder}\{fileName}_{partNumber++}.pdf";
                    this.SplitFileNames.Add(newFileName);
                    return new PdfWriter(newFileName);
                }
            }
        }

 PdfHelper helper = new PdfHelper();
 List<string> files = helper.SplitPDF(@"<file path>\<filename>.pdf", 500);
© www.soinside.com 2019 - 2024. All rights reserved.