我正在尝试使用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();
}
}
答案 0 :(得分:3)
欢迎来到地狱。保持一段时间: - )
Java使用一些复杂的代码来布局打印机的文本(因此它不会发送print "Text" with a bold font
,而是select Times-Bold
,Move the cursor to x,y
,Draw the letter "T"
,{{1} ,画出字母“e”,......`
您的问题是Java和您的打印机对字符的宽度有不同的想法。如果仔细观察,粗体字Move to x2,y
的字母会有点分开。
你怎么解决这个问题?尝试不同的字体,直到它工作。我不知道用Java print 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?)。