在C#中将空白.txt文件转换为PDF

时间:2011-03-31 14:28:21

标签: c# pdf pdf-generation itextsharp

我在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);
        }
    }

如果需要任何信息,请告诉我。

感谢

2 个答案:

答案 0 :(得分:1)

您需要在pdf中添加一些内容。所以试试这个:

myString = string.IsNullOrEmpty(myString) ? " " : myString;
document.Add(new iTextSharp.text.Paragraph(myString));

答案 1 :(得分:1)

您需要说服iText该页面上有某些内容。

两种方法:

  1. 明确。 writer.setPageEmpty(false);
  2. 欺骗它(这是达林建议的)。 writer.getDirectContent().setLiteral(" ");