我正在使用 android studio 制作一个 java 桌面应用程序(bcz 还没有其他可用工具)。 在我的应用程序中,我必须添加一个打印按钮,该按钮从 jtextarea 获取文本,将其转换为 pdf,然后打印。 我不知道该怎么做。我在互联网上搜索过但没有找到任何有用的 Material 。 我使用了 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();
}
}
如果文本超过一页,则不会打印该文本。 任何帮助将非常感激。 谢谢。
最佳答案
对 PDF 打印的支持取决于平台。如果您只想打印文本,可以使用 java.awt.font.LineBreak Measurer
将文本拆分为行和页。
关于java - 将java文本转换为pdf然后打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49047224/