【问题标题】:How to correctly print out a hard copy of a JTextPane with "text/rtf" content?如何正确打印出带有“text/rtf”内容的 JTextPane 的硬拷贝?
【发布时间】:2010-09-27 14:14:48
【问题描述】:

我正在尝试使用JTextPane 将一些简单的 RTF 格式文本打印到 激光打印机

在软件 PDF 打印机 (FreePDF XP) 上的结果看起来不错,但是当打印到真正的打印机时,文本的格式化部分之间没有适当的空间。

编辑:我上传了一个示例输出(底部是扫描的打印输出)

Example http://ompldr.org/vNXo4Zg/output.png

在我看来,Graphics 对象开始绘制 RTF 代码的各个部分存在问题。好像它无法确定正确放置每个部分的位置(X 坐标)。

我必须提供某种坐标系转换吗?

使用的简单测试代码:

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.swing.JFrame;
import javax.swing.JTextPane;

class MyTextComp extends JTextPane implements Printable
{
  public MyTextComp()
  {
    setContentType("text/rtf");
    setText("{\\rtf1 HelloWorld! \\par {\\i This} is formatted {\\b Text}.}");
  }

  public void paintComponent(Graphics g)
  {
    super.paintComponent(g);
  }

  public int print(Graphics g, PageFormat pf, int pIndex)
  {
    if(pIndex > 0)
      return Printable.NO_SUCH_PAGE;

    Graphics2D g2d = (Graphics2D)g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());

    /* Now print the window and its visible contents */
    printAll(g);
    return Printable.PAGE_EXISTS;
  }
}

public class TextCompPrint extends JFrame
{ 
  public static void main(String[] args) throws PrinterException
  {
    TextCompPrint myFrame = new TextCompPrint();
    MyTextComp    myComp  = new MyTextComp();

    myFrame.add(myComp, BorderLayout.CENTER);
    myFrame.setSize(200, 200);
    myFrame.setVisible(true);

    PrinterJob pj = PrinterJob.getPrinterJob(); 
    pj.setPrintable(myComp);
    pj.print();
  }
}

【问题讨论】:

    标签: java printing rtf jtextpane


    【解决方案1】:

    欢迎来到地狱。呆一会儿:-)

    Java 使用一些复杂的代码来布局打印机的文本(因此它不会发送print "Text" with a bold font,而是发送select Times-BoldMove the cursor to x,yDraw the letter "T"Move to x2,y、绘制字母“e”、. ..`

    您的问题是 Java 和您的打印机对字符的宽度有不同的想法。仔细看,粗体字Text的字母间距有点大。

    你怎么能解决这个问题?尝试不同的字体,直到它起作用。我不知道用 Java 打印 API 下载轮廓字体的任何方法。

    或者使用PDFBox自己生成PDF。

    [编辑] Java 不是 DTP 系统。打印支持充其量只是基本的。

    如果您需要更多,请考虑使用 OpenOffice 将 RTF 转换为 PDF 以进行打印(请参阅 Is there a free way to convert RTF to PDF?How can I use OpenOffice in server mode as a multithreaded service?)。

    use OpenOffice as text pane

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多