使用iText将jcomponent导出为PDF [英] export jcomponent to PDF with iText

查看:151
本文介绍了使用iText将jcomponent导出为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Id like to export my jcomponent (custom paintcomponent method which draws a lot of texts and lines, small images (kind of a small word application)) to PDF

我的组件是bill

我使用的方法(有效,但有些方法已弃用)是:

the method i use for this (which works, but some methods are deprecated) is:

       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打印在一个页面上。

It works quite well, but there are two big problems: the method tp.createGraphics is deprecated (so there might be a better solution) and If the swing Component is very big, it is printed on just one single page in PDF.

所以我需要的是一个页面-splitter帮助我创建A4大小的页面,以便打印。当jcomponent非常大的时候没有缓冲区溢出...

So what i need is a "page-splitter" to help me creating A4 sized pages to be print-friendly. Of course without a buffer overflow when the jcomponent is very big...

有人可以帮忙吗?

推荐答案

执行此操作的官方Java方式是让您的JComponent实现Pageable和/或Printable,以便它知道如何将自身的一部分绘制到页面上(由Graphics表示) 。通常,在Printable.print(图形图形,PageFormat pageFormat,int pageIndex)方法中,您可以将图形转换为pageIndex的一些常数Y因子乘以标题,间隔物等...

The "official Java" way to do this would be for your JComponent to implement Pageable and/or Printable, so that it knows how to draw portions of itself onto a page (represented by a Graphics). Typically, in the Printable.print(Graphics graphics, PageFormat pageFormat, int pageIndex) method, you would translate the graphics by some constant Y factor times the pageIndex, accounting for headers, spacers, etc...

这样它也可以打印成纸。

That way it can print out to paper too.

PDF代码是非常接近你所拥有的,你每页只做一次。你可以在这里找到我博客上的代码,这是基于 Gert-Jan Schouten先前的工作

The PDF code is very close to what you have, you just do it once per page. You can find code on my blog here, which is based upon earlier work by Gert-Jan Schouten here

这篇关于使用iText将jcomponent导出为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆