2017-01-10 5 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 делает работу правильно, однако Pane анализируется как graphics2D компонента, и так оберточную линию не представляется возможным.

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; 
} 

с,

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

Я ищу решение, основанное на внешней библиотеке, я попытался expermenting с IText и PDFBox, но безрезультатно до сих пор.

Я хочу отметить, что в приведенном выше решении используется библиотека com.lowagie.

+0

Вы хотите сохранить форму панели редактора или текста в нем? – Frakcool

+0

Текст, и просто для ясности, JEditorPane можно изменить на JtextPane или JTextArea, в зависимости от решения, которое вы имеете в виду. –

+0

Сначала вы можете использовать StandardPrint, чтобы превратить ваш JEditorPane (или другой компонент) в изображение, а затем преобразовать его в PDF с помощью lowagie: https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/ print/StandardPrint.java – ControlAltDel

ответ

1

Из того, что я понимаю, вы хотите преобразовать свой графический интерфейс в изображения и распечатать его в формате PDF, если это не то, что вы хотите, пожалуйста, уточните.

Вот простая программа, которая создает следующий графический интерфейс (без текста, написанного на нем), который является JTextArea и JButton.

enter image description here

При нажатии на кнопку открывается новый документ, занимает площадь и преобразует его в изображение, а затем добавляет, что изображение в формате PDF, а затем делает то же самое с кнопкой, так что вы получите аналогичный выход в формате PDF, как это:

enter image description here

хитрость заключается в том, чтобы использовать как java.awt.Image и com.itextpdf.text.Image, бывший преобразовать JComponent к изображениям и последним для их печати в PDF, этот трюк был найден и основанный на этом 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); 
    } 
}