2017-01-10 2 views
0

保存ボタンをクリックすると、JEditorPaneからPDFとしてテキストを保存しようとしています。JEditorPaneをPDFとして保存する方法は?

saveAs.addActionListener(new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent e) { 

      String title = JOptionPane.showInputDialog(null, "Enter a name for file..."); 
      try{ 
       paintToPDF(newBlanktoEdit, title); 
      }catch (Exception exc){ 
       exc.printStackTrace(); 
      } 
     } 
    }); 

正しく仕事をしpaintToPDF方法は、しかしながら、Panegraphics2D成分として解析され、そのためラインを包むことは不可能です。

int inch = Toolkit.getDefaultToolkit().getScreenResolution(); 
float pixelToPoint = (float) 72/(float) inch; 

、と

protected void paintToPDF(JEditorPane newPane, String title) throws Exception{ 

    newPane.setBounds(0, 0, (int) convertToPixels(612 - 58), (int) convertToPixels(792 - 60)); 

    Document doc = new Document(); 
    FileOutputStream out = new FileOutputStream(title + ".pdf"); 
    PdfWriter writer = PdfWriter.getInstance(doc, out); 

    doc.setPageSize(new com.lowagie.text.Rectangle(612, 792)); 
    doc.open(); 
    PdfContentByte cb = writer.getDirectContent(); 
    cb.saveState(); 
    cb.concatCTM(1, 0, 0, 1, 0, 0); 

    DefaultFontMapper mapper = new DefaultFontMapper(); 
    mapper.insertDirectory("c:/windows/fonts"); 

    Graphics2D g = cb.createGraphics(612, 792, mapper, true, .92f); 

    AffineTransform at = new AffineTransform(); 
    at.translate(convertToPixels(20), convertToPixels(20)); 
    at.scale(pixelToPoint, pixelToPoint); 

    g.transform(at); 
    g.setColor(Color.WHITE); 
    g.fill(newPane.getBounds()); 

    Rectangle alloc = getVisivleEditorRect(newPane); 
    newPane.getUI().getRootView(newPane).paint(g, alloc); 

    g.setColor(Color.BLACK); 
    g.draw(newPane.getBounds()); 

    g.dispose(); 
    cb.restoreState(); 
    doc.close(); 
    out.flush(); 
    out.close(); 
} 

private float convertToPixels(int points){ 

    return (float) (points/pixelToPoint); 
} 

private Rectangle getVisivleEditorRect(JEditorPane newPane){ 

    Rectangle alloc = newPane.getBounds(); 
    if((alloc.width > 0) && (alloc.height > 0)){ 
     alloc.x = alloc.y = 0; 
     Insets insets = newPane.getInsets(); 
     alloc.x += insets.left; 
     alloc.y += insets.top; 
     alloc.width -= insets.left + insets.right; 
     alloc.height -= insets.top + insets.bottom; 
     return alloc; 
    } 
    return null; 
} 

私は外部のライブラリに基づいて解決策を探しています、私は、これまで無駄に、iTextのとPDFBoxでexpermentingてみました。

上記の解決方法は、com.lowagieライブラリを使用していることを指摘します。

+0

は? – Frakcool

+0

テキストは、分かりやすくするために、あなたが気をつけている解決策に応じて、JTextPaneまたはJTextAreaに変更することができます。 –

+0

StandardPrintを使用してJEditorPane(または他のComponent)ディスプレイをImageに変換し、lowagieを使用してPDFに変換できます。https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/ print/StandardPrint.java – ControlAltDel

答えて

1

あなたのGUIを画像に変換してPDFで印刷したいと思っているところから、これが明確でない場合は、明確にしてください。

次のGUIを作成する簡単なプログラムです(テキストは書かれていません)。JTextAreaJButtonです。

enter image description here

クリックすると、ボタンは、新しいドキュメントを開き、地域を取り、画像に変換し、次にPDFにその画像を追加し、後であなたが類似し得るので、ボタンと同じことを行いますこのようなPDFでの出力:

enter image description here

トリックは、画像やPDFでそれらを印刷するには、後者にJComponentを変換する前の、java.awt.Imagecom.itextpdf.text.Imageの両方を使用することで、このトリックが発見されたとこのpeeskillet'sに基づいてanswer

ので、更なる説明もなく、ここで上記の結果を達成するコードです:あなたはエディタペインのフォームまたはそれにテキストを保存したい

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.image.BufferedImage; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 

import javax.swing.BorderFactory; 
import javax.swing.JButton; 
import javax.swing.JComponent; 
import javax.swing.JFrame; 
import javax.swing.JTextArea; 
import javax.swing.SwingUtilities; 

import com.itextpdf.text.Document; 
import com.itextpdf.text.DocumentException; 
import com.itextpdf.text.Image; 
import com.itextpdf.text.PageSize; 
import com.itextpdf.text.pdf.PdfWriter; 

public class PdfFromUserInput { 

    private JFrame frame; 
    private JTextArea area; 
    private JButton button; 
    private Document document; 
    private PdfWriter writer; 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       new PdfFromUserInput().createAndShowGui(); 
      } 
     }); 
    } 

    public void openPdf() throws FileNotFoundException, DocumentException { 
     document = new Document(PageSize.A4, 30, 30, 30, 30); 
     writer = PdfWriter.getInstance(document, new FileOutputStream("myFile.pdf")); 
     document.open(); 
    } 

    public void closePdf() { 
     document.close(); 
    } 

    public java.awt.Image getImageFromComponent(JComponent component) throws DocumentException { 
     BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_RGB); 
     component.paint(image.getGraphics()); 
     return image; 
    } 

    public void addImageToDocument(java.awt.Image img) throws IOException, DocumentException { 
     Image image = Image.getInstance(writer, img, 1); 
     image.scalePercent(50); 
     document.add(image); 
     System.out.println("printed!"); 
    } 

    public void createAndShowGui() { 
     frame = new JFrame("PDF creator"); 
     area = new JTextArea(10, 30); 
     area.setBorder(BorderFactory.createLineBorder(Color.RED)); 
     button = new JButton("Create PDF"); 

     button.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       try { 
        openPdf(); 
        java.awt.Image img = getImageFromComponent(area); 
        addImageToDocument(img); 
        img = getImageFromComponent(button); 
        addImageToDocument(img); 
        closePdf(); 
       } catch (DocumentException e1) { 
        e1.printStackTrace(); 
       } catch (FileNotFoundException e1) { 
        e1.printStackTrace(); 
       } catch (IOException e1) { 
        e1.printStackTrace(); 
       } 
      } 
     }); 

     frame.add(area, BorderLayout.CENTER); 
     frame.add(button, BorderLayout.SOUTH); 

     frame.pack(); 
     frame.setVisible(true); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 
} 
関連する問題