Я пытаюсь сохранить текст с 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
.
Вы хотите сохранить форму панели редактора или текста в нем? – Frakcool
Текст, и просто для ясности, JEditorPane можно изменить на JtextPane или JTextArea, в зависимости от решения, которое вы имеете в виду. –
Сначала вы можете использовать StandardPrint, чтобы превратить ваш JEditorPane (или другой компонент) в изображение, а затем преобразовать его в PDF с помощью lowagie: https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/ print/StandardPrint.java – ControlAltDel