I'm trying to save text from a JEditorPane as a pdf once a save button is clicked.
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();
}
}
});
The method paintToPDF
does the job correctly, however the Pane
is parsed as a graphics2D
component, and so wrapping the line is not possible.
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;
}
with,
int inch = Toolkit.getDefaultToolkit().getScreenResolution();
float pixelToPoint = (float) 72 / (float) inch;
I'm looking for a solution based on an external library, i tried expermenting with iText and PDFBox, to no avail so far.
I want to point out that the solution above uses com.lowagie
library.