【问题标题】:export jcomponent to PDF with iText使用 iText 将 jcomponent 导出为 PDF
【发布时间】:2023-03-29 16:09:02
【问题描述】:

我想将我的 jcomponent(绘制大量文本和线条、小图像(一种小文字应用程序)的自定义 paintcomponent 方法)导出到 PDF

我的组件是“bill”

我为此使用的方法(可行,但不推荐使用某些方法)是:

       com.itextpdf.text.Rectangle r = new com.itextpdf.text.Rectangle(0,0,bill.getWidth(),bill.getHeight());

       Document document = new Document(r);

       try {
          PdfWriter writer;
          writer = PdfWriter.getInstance(document, new FileOutputStream(f));
          document.open();
          PdfContentByte cb = writer.getDirectContent();
          PdfTemplate tp = cb.createTemplate(bill.getWidth(), bill.getHeight());
          Graphics2D g2d = tp.createGraphics(bill.getWidth(), bill.getHeight(), new DefaultFontMapper());

          bill.addNotify();
          bill.validate();

          bill.paint(g2d);
          g2d.dispose();

          cb.addTemplate(tp, 0, 0);
       }
       catch(Exception e) {
          e.printStackTrace();
       }

       document.close();

它工作得很好,但有两个大问题:方法 tp.createGraphics 已被弃用(因此可能有更好的解决方案)和如果 swing 组件非常大,它只会打印在 PDF 中的一页上.

所以我需要一个“分页器”来帮助我创建 A4 大小的页面以方便打印。当jcomponent非常大时当然没有缓冲区溢出......

谁能帮忙?

【问题讨论】:

    标签: java swing pdf itext jcomponent


    【解决方案1】:

    执行此操作的“官方 Java”方法是让您的 JComponent 实现 Pageable 和/或 Printable,以便它知道如何将自身的一部分绘制到页面上(由图形表示)。通常情况下,in the Printable.print(Graphics graphics, PageFormat pageFormat, int pageIndex) 方法,您可以通过一些常数 Y 因子乘以 pageIndex 来转换图形,包括页眉、分隔符等...

    这样它也可以打印到纸上。

    PDF 代码与您所拥有的非常接近,您只需每页执行一次。你可以找到code on my blog here,它基于earlier work by Gert-Jan Schouten here

    【讨论】:

      猜你喜欢
      • 2014-08-22
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-04
      相关资源
      最近更新 更多