hahahakebab
hahahakebab

Reputation: 326

Changing print margins on JTextPane

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.

Upvotes: 0

Views: 670

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347334

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)

NormalModified

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

Upvotes: 2

Related Questions