2011-01-05 93 views
3

嗨我創建了一個PDF文件,其中包含一個圖像,我想在創建後打印我的pdf。如果我在內存中使用PDF而不是有文件,然後將其發送給打印機,那麼更好......任何想法?如何打印使用iText創建的PDF?

我正在使用iText。檢查我的代碼:

import com.lowagie.text.Document; 
    import com.lowagie.text.DocumentException; 
    import com.lowagie.text.Image; 
    import com.lowagie.text.PageSize; 
    import com.lowagie.text.Rectangle; 
    import com.lowagie.text.pdf.PdfContentByte; 
    import com.lowagie.text.pdf.PdfPrinterGraphics2D; 
    import com.lowagie.text.pdf.PdfTemplate; 
    import com.lowagie.text.pdf.PdfWriter; 

    import javax.imageio.ImageIO; 

    import java.awt.Color; 
    import java.awt.Graphics2D; 
    import java.awt.Toolkit; 
    import java.awt.image.BufferedImage; 
    import java.io.ByteArrayInputStream; 
    import java.io.File; 
    import java.io.FileOutputStream; 
    import java.io.IOException; 
    import java.io.InputStream; 


     private boolean exportToPdfThroughPNG(String fileName, float width, float height) throws DocumentException, IOException { 
     logger.debug("[boolean exportToPdfQuick() throws IOException, DocumentException]"); 

     BufferedImage pngFile = createPngFile(); 

     Document document = new Document(); 
     document.setPageSize(new Rectangle(width, height)); 
     PdfWriter.getInstance(document, new FileOutputStream(fileName)); 
     document.open(); 
     Image image = Image.getInstance(Toolkit.getDefaultToolkit().createImage(pngFile.getSource()), Color.WHITE); 
     document.add(image); 
     // If some day anyone wants to put text in the pdf. @Eduardo 
     // document.add(new Paragraph("title of the process")); 
     document.close(); 

     return true; 
    } 

在此先感謝!

+0

這是在Windows上還是在不同的平臺上運行? – 2011-01-06 13:48:27

回答

1

您始終可以使用ByteArrayOutputStream而不是FileOutputStream。

有了PDF字節後,它就成了一個正常的「你怎麼用Java打印」的問題。許多打印機(或者至少他們的驅動程序)現在都會直接使用PDF,所以在那個時候可以爭辯說你已經完成了。 PS:一旦我標記了你的問題「Java」,它會使用「導入」作爲關鍵字等將代碼塊着色。將來需要記住的東西。

+0

謝謝馬克,我工作上很累,終於可以解決這個問題... PS:我沒有專家使用這個編輯器!抱歉! – MadMad666 2011-01-07 05:18:38