Lam*_*ost 10 c# pdf-generation xpsdocument itextsharp spire.doc
我正在尝试使用FreeSpire将安全的PDF转换为XPS并返回PDF,然后使用iTextSharp将它们组合在一起.下面是我转换各种文件的代码段.
char[] delimiter = { '\\' };
string WorkDir = @"C:\Users\rwong\Desktop\PDF\Test";
Directory.SetCurrentDirectory(WorkDir);
string[] SubWorkDir = Directory.GetDirectories(WorkDir);
//convert items to PDF
foreach (string subdir in SubWorkDir)
{
string[] Loan_list = Directory.GetFiles(subdir);
for (int f = 0; f < Loan_list.Length - 1; f++)
{
if (Loan_list[f].EndsWith(".doc") || Loan_list[f].EndsWith(".DOC"))
{
Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
doc.LoadFromFile(Loan_list[f], FileFormat.DOC);
doc.SaveToFile((Path.ChangeExtension(Loan_list[f],".pdf")), FileFormat.PDF);
doc.Close();
}
. //other extension cases
.
.
else if (Loan_list[f].EndsWith(".pdf") || Loan_list[f].EndsWith(".PDF"))
{
PdfReader reader = new PdfReader(Loan_list[f]);
bool PDFCheck = reader.IsOpenedWithFullPermissions;
reader.Close();
if (PDFCheck)
{
Console.WriteLine("{0}\\Full Permisions", Loan_list[f]);
reader.Close();
}
else
{
Console.WriteLine("{0}\\Secured", Loan_list[f]);
Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
string path = Loan_List[f];
doc.LoadFromFile(Loan_list[f]);
doc.SaveToFile((Path.ChangeExtension(Loan_list[f], ".xps")), FileFormat.XPS);
doc.Close();
Spire.Pdf.PdfDocument doc2 = new Spire.Pdf.PdfDocument();
doc2.LoadFromFile((Path.ChangeExtension(Loan_list[f], ".xps")), FileFormat.XPS);
doc2.SaveToFile(Loan_list[f], FileFormat.PDF);
doc2.Close();
}
Run Code Online (Sandbox Code Playgroud)
问题是我得到了Value cannot be null error.doc.LoadFromFile(Loan_list[f]);我string path = Loan_list[f];要检查Loan_list [f]是否为空,但事实并非如此.我试图Loan_list[f]用变量named 替换参数,path但它也不会.我测试了PDF转换的规模较小(见下文)
string PDFDoc = @"C:\Users\rwong\Desktop\Test\Test\Test.PDF";
string XPSDoc = @"C:\Users\rwong\Desktop\Test\Test\Test.xps";
//Convert PDF file to XPS file
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(PDFDoc);
doc.SaveToFile(XPSDoc, FileFormat.XPS);
doc.Close();
//Convert XPS file to PDF
PdfDocument doc2 = new PdfDocument();
doc2.LoadFromFile(XPSDoc, FileFormat.XPS);
doc2.SaveToFile(PDFDoc, FileFormat.PDF);
doc2.Close();
Run Code Online (Sandbox Code Playgroud)
我想了解为什么我收到此错误以及如何解决它.
对于您面临的问题,有两种解决方案。
获取对象中的文档Document而不是PDFDocument. 然后可能会尝试SaveToFile这样的事情
Document document = new Document();
//Load a Document in document Object
document.SaveToFile("Sample.pdf", FileFormat.PDF);
Run Code Online (Sandbox Code Playgroud)您可以使用 Stream 来完成类似的事情
PdfDocument doc = new PdfDocument();
//Load PDF file from stream.
FileStream from_stream = File.OpenRead(Loan_list[f]);
//Make sure the Loan_list[f] is the complete path of the file with extension.
doc.LoadFromStream(from_stream);
//Save the PDF document.
doc.SaveToFile(Loan_list[f] + ".pdf",FileFormat.PDF);
Run Code Online (Sandbox Code Playgroud)第二种方法是简单的方法,但我建议您使用第一种方法,因为显而易见的原因,例如文档将提供比流更好的可转换性。由于文档有章节、段落、页面设置、文本、字体,因此需要进行更好或精确的格式设置。