更改 JTextPane 上的打印边距 [英] Changing print margins on JTextPane

查看:47
本文介绍了更改 JTextPane 上的打印边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到过各种在 Java 中打印时更改边距的解决方案,但似乎都没有.

还有对话方式...

protected static double fromCMToPPI(double cm) {返回到 PPI(cm * 0.393700787);}受保护的静态双到PPI(双英寸){返回英寸 * 72d;}

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

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

I have come across various solutions to changing the margins when printing in Java but none seem to work. Here and Here.

What I have so far is,

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();

When using the inbuilt print method the margins are set to default as 25.4mm. I'd like to be able to edit these margins while still being able to have a print dialog.

解决方案

What I "can" verify is, something like this will effect the page size and margins of the output

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();
}

Normal output vs modified output (border added after to highlight change)

And the conversation methods...

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

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

What I can't verify is if those values appear in either page setup or printer dialogs, as MacOS has decided I don't need to see them :/

From previous experience on Windows, I seem to remember it working

这篇关于更改 JTextPane 上的打印边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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