2011-04-18 47 views
1

我試圖用Java編寫PDF文件說一個PDF hello neckbeards但是當我運行我的程序,則Adobe Reader打開,但一個錯誤出現說的話:生成的Java

There was an error opening this document. 
The file is already open or in use by another application. 

這裏是我的代碼:

import java.awt.Desktop; 
import java.io.*; 

public class count10 { 

    public static void main(String[] args) throws Exception { 

     File tempfile = File.createTempFile("report", ".pdf"); 
     FileWriter pfile = new FileWriter(tempfile); 
     pfile.write("hello neckbeards"); 

     Desktop dtop = null; 

     if (Desktop.isDesktopSupported()) { 
      dtop = Desktop.getDesktop(); 
     } 
     if (dtop.isSupported(Desktop.Action.OPEN)){ 
      String path = tempfile.getPath(); 
      dtop.open(new File(path)); 
     } 
    } 
} 
+0

由於幾個人在下面所提到的,iText的是要建立PDF文件的好方法。請在任何重大開發之前查看iText的許可證。 – hooknc 2011-04-18 16:17:41

+2

哇。這不會成爲一項家庭作業嗎? – 2011-04-18 22:22:20

+0

'@ neckbeard69' ** 1)**如果這是家庭作業,請用'homework'標記標記。 ** 2)**當您找到答案解決您的問題時,請在接近選票區域時通過檢查其**綠色勾號**接受**。謝謝! – 2011-10-12 18:22:09

回答

4

要創建一個PDF文件,您可以使用庫,如iText。在我看來,你只是簡單地創建一個純文本文件,然後嘗試用PDF閱讀器打開它。

4

在您寫入您的文件後,您必須關閉它,使用pfile.close();

請注意,您所寫的只是一個文本文件,其內容爲hello neckbeards和擴展.pdf。它是而不是在正常意義上的PDF文件,可以用Adobe Reader等PDF閱讀器打開。

使用類似iText的庫來創建真實的PDF文件。

一個文件必須遵循PDF implementation(PDF文件)作爲有效的PDF文件。正如你所看到的,這涉及更多,而不僅僅是將文本寫入文件。

0

我不熟悉以這種方式從桌面打開文件,但寫入文件後值得關閉FileWriter。順便說一下,我發現XSLT是生成PDF文檔的好方法,因爲您可以對輸出和持續維護進行大量控制,並且不需要重新編譯代碼(如果您擁有市場營銷部門誰喜歡改變他們的想法)。如果您有興趣,請查看XSL-FO,Apache FOP是一個很好的實現。

5

這裏有許多錯誤:

  • 你正在寫純文本。由於該文件不是有效的PDF文件,因此Adobe Reader將引發錯誤!
    要編寫PDF,請使用類似iText或PDFBox的庫。

  • 在您可以編寫或讀取文件之前,您需要從您的程序到該文件的連接打開
    因此,當您結束寫入/讀取文件時,不要忘記關閉連接,以便其他程序(例如Adobe Reader)也可以讀取文件!若要關閉文件,只需做:

    pfile.close(); 
    
  • main方法不應該拋出任何異常。相反,如果發生錯誤,則需要捕獲必需的並執行適當的操作(告訴用戶,退出...)。 讀/寫文件(或任何東西),這是推薦結構

    FileReader reader = null; 
    try { 
        reader = new FileReader("file.txt"); //open the file 
    
        //read or write the file 
    
    } catch (IOException ex) { 
        //warn the user, log the error, ... 
    } finally { 
        if (reader != null) reader.close(); //always close the file when finished 
    } 
    
  • 最終if地方。正確的代碼是:

    if (Desktop.isDesktopSupported()) { 
        Desktop dtop = Desktop.getDesktop(); 
        if (dtop.isSupported(Desktop.Action.OPEN)) { 
         dtop.open(tempfile); 
        } 
    } 
    

    同樣,我稱之爲open方法傳遞文件直接通知。
    有沒有必要複製它。

0
Try this code.... 
    Document document=new Document(); 
    PdfWriter.getInstance(document,new FileOutputStream("E:/data.pdf")); 
    document.open(); 
    PdfPTable table=new PdfPTable(2); 
       table.addCell("Employee ID"); 
       table.addCell("Employee Name"); 
       table.addCell("1"); 
       table.addCell("Temperary Employee"); 
       document.add(table); 
       document.close(); 

You have to import.... 
import com.itextpdf.text.Document; 
import com.itextpdf.text.DocumentException; 
import com.itextpdf.text.pdf.PdfPTable; 
import com.itextpdf.text.pdf.PdfWriter;