2011-03-31 55 views
0

我將.txt轉換爲.pdf。如果.txt文件不是空白,此工作正常。如果是,它會拋出「文檔沒有頁面」的錯誤。將C#中的空白.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

沒有評論...? :-( – 2011-03-31 14:35:31

+0

)你真的想要一個空白的PDF生成嗎?可能有什麼用途?爲什麼不首先檢查文本文件的內容,如果它是空白的則拋出一個消息框? – MAW74656 2011-03-31 16:24:41

+0

@MAW:我知道它是沒有用來生成一個空白的PDF,但你知道測試人員,他們測試的一切..林:-) – 2011-03-31 17:35:49

回答

1

您需要添加一些內容到PDF。所以試試這個吧:

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

感謝您的評論。但仍然拋出同樣的錯誤! :-( – 2011-03-31 14:44:15

+1

@Xor power:什麼錯誤?這對我有效。你使用的是什麼版本的iTextSharp? – 2011-03-31 15:30:33

+0

順便說一句,也許你也想關閉'writer'。 – 2011-03-31 15:32:20

1

你需要說服iText那個頁面上有東西。

兩個方法:

  1. 要明確。 writer.setPageEmpty(false);
  2. 欺騙它(這是達林所暗示的)。 writer.getDirectContent().setLiteral(" ");