我正在使用android studio制作一个java桌面应用程序(bcz还没有其他可用的工具)。在我的应用程序中,我必须添加一个打印按钮,它从jtextarea获取文本,将其转换为pdf,然后打印它。我不知道该怎么做。我已经在网上搜索过了,但没有找到任何有用的材料。我使用的是printerjob,但它将整个组件打印为图像。如下所示:
public class Printer implements Printable {
final Component comp;
public Printer(Component comp){
this.comp = comp;
}
@Override
public int print(Graphics graphics, PageFormat format, int page_index) throws PrinterException {
if (page_index > 0) {
return Printable.NO_SUCH_PAGE;
}
// get the bounds of the component
Dimension dim = comp.getSize();
double cHeight = dim.getHeight();
double cWidth = dim.getWidth();
// get the bounds of the printable area
double pHeight = format.getImageableHeight();
double pWidth = format.getImageableWidth();
double pXStart = format.getImageableX();
double pYStart = format.getImageableY();
double xRatio = pWidth / cWidth;
double yRatio = pHeight / cHeight;
Graphics2D g2 = (Graphics2D) graphics;
g2.translate(pXStart, pYStart);
//g2.scale(xRatio, yRatio);
comp.print(g2);
return Printable.PAGE_EXISTS;
}
}
public void printComponent() throws PrinterException {
PrinterJob pjob = PrinterJob.getPrinterJob();
PageFormat preformat = pjob.defaultPage();
preformat.setOrientation(PageFormat.PORTRAIT);
PageFormat postformat = pjob.pageDialog(preformat);
//If user does not hit cancel then print.
if (preformat != postformat) {
//Set print component
pjob.setPrintable(new Printer(bluetoothText), postformat);
if (pjob.printDialog()) {
pjob.print();
}
}如果文本超过一页,则不会打印该文本。任何帮助都将是非常有用的。谢谢。
发布于 2018-03-01 18:27:43
对PDF打印的支持依赖于平台。如果只想打印文本,可以使用java.awt.font.LineBreakMeasurer将文本拆分为行和页。
https://stackoverflow.com/questions/49047224
复制相似问题