首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将java文本转换为pdf,然后打印出来

将java文本转换为pdf,然后打印出来
EN

Stack Overflow用户
提问于 2018-03-01 18:07:19
回答 1查看 64关注 0票数 1

我正在使用android studio制作一个java桌面应用程序(bcz还没有其他可用的工具)。在我的应用程序中,我必须添加一个打印按钮,它从jtextarea获取文本,将其转换为pdf,然后打印它。我不知道该怎么做。我已经在网上搜索过了,但没有找到任何有用的材料。我使用的是printerjob,但它将整个组件打印为图像。如下所示:

代码语言:javascript
复制
 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();
            }
        }

如果文本超过一页,则不会打印该文本。任何帮助都将是非常有用的。谢谢。

EN

回答 1

Stack Overflow用户

发布于 2018-03-01 18:27:43

对PDF打印的支持依赖于平台。如果只想打印文本,可以使用java.awt.font.LineBreakMeasurer将文本拆分为行和页。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49047224

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档