【问题标题】:Changing print margins on JTextPane更改 JTextPane 上的打印边距
【发布时间】:2017-11-06 23:39:23
【问题描述】:

我遇到了各种在 Java 中打印时更改页边距的解决方案,但似乎都不起作用。 HereHere

到目前为止,我所拥有的是,

TextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();

//  Define a keyword attribute
SimpleAttributeSet keyWord = new SimpleAttributeSet();
StyleConstants.setBold(keyWord, true);

Style style = doc.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon(qrcode));

doc.insertString(0, "Title Here\n", null );
doc.insertString(doc.getLength(), "Ignored", style);

textPane.print();

使用内置打印方法时,边距默认设置为 25.4mm。我希望能够编辑这些边距同时仍然能够有一个打印对话框

【问题讨论】:

  • 打印对话框不提供“页面设置”选项卡吗?
  • @MadProgrammer 是的,但我希望程序设置这个值。

标签: java printing margins


【解决方案1】:

我“可以”验证的是,这样的事情会影响输出的页面大小和边距

JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();

//  Define a keyword attribute
SimpleAttributeSet keyWord = new SimpleAttributeSet();
StyleConstants.setBold(keyWord, true);

Style style = doc.addStyle("StyleName", null);
//StyleConstants.setIcon(style, new ImageIcon(qrcode));

doc.insertString(0, "Title Here\n", null);
doc.insertString(doc.getLength(), "Ignored", style);

Paper paper = new Paper();
paper.setSize(fromCMToPPI(21.0), fromCMToPPI(29.7)); // A4
paper.setImageableArea(fromCMToPPI(5.0), fromCMToPPI(5.0), 
                fromCMToPPI(21.0) - fromCMToPPI(10.0), fromCMToPPI(29.7) - fromCMToPPI(10.0));

PageFormat pageFormat = new PageFormat();
pageFormat.setPaper(paper);

PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPrintable(textPane.getPrintable(null, null), pageFormat);
PageFormat pf = pj.pageDialog(pageFormat);
if (pj.printDialog()) {
    pj.print();
}

正常输出与修改后的输出(后添加边框以突出显示更改)

还有对话方式……

protected static double fromCMToPPI(double cm) {
    return toPPI(cm * 0.393700787);
}

protected static double toPPI(double inch) {
    return inch * 72d;
}

我无法验证的是这些值是否出现在页面设置或打印机对话框中,因为 MacOS 已决定我不需要查看它们:/

根据以前在 Windows 上的经验,我似乎记得它可以工作

【讨论】:

  • 感谢回复,但变量“pj”指的是什么?
  • @hahahakebab 应该是PrinterJob pj = PrinterJob.getPrinterJob();,我已经更新了例子
  • 仅供参考,这些值不会出现在打印机对话框中,但会出现在页面设置中。我在 Windows 10 上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-31
  • 1970-01-01
相关资源
最近更新 更多