我在c#中将.txt转换为.pdf。如果.txt文件不为空,则此方法正常。如果是,它会抛出“文件没有页面”的错误。
生成pdf但在打开pdf文件时出现“打开此文档时出错。文件已损坏且无法修复”的错误。
代码如下所示
public void converttxttoPDF(string sourcePath, string destPath)
{
try
{
iTextSharp.text.Document document = new iTextSharp.text.Document();
string filename = Path.GetFileNameWithoutExtension(sourcePath);
System.IO.StreamReader myFile = new System.IO.StreamReader(sourcePath);
string myString = myFile.ReadToEnd();
myFile.Close();
if (!Directory.Exists(destPath))
Directory.CreateDirectory(destPath);
iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(destPath + "\\" + filename + ".pdf", FileMode.CreateNew));
document.Open();
document.Add(new iTextSharp.text.Paragraph(myString));
document.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
如果需要任何信息,请告诉我。
感谢
答案 0 :(得分:1)
您需要在pdf中添加一些内容。所以试试这个:
myString = string.IsNullOrEmpty(myString) ? " " : myString;
document.Add(new iTextSharp.text.Paragraph(myString));
答案 1 :(得分:1)
您需要说服iText该页面上有某些内容。
两种方法:
writer.setPageEmpty(false);
writer.getDirectContent().setLiteral(" ");