JPanelを印刷しようとしていますが、作業コードがあります。しかし、問題は、それは4つの側面から広範なmaginとJPanelを印刷している... Plzの誰かが私のコードをチェックします。そして私に提案してください、どのようにして最小限のマージンでa4サイズの用紙に適したコードを変更できますか? 0.5インチ縦、横方向に1インチ:そしてactioperformedJavaコードで印刷する余白を設定します
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
PrinterJob pjob = PrinterJob.getPrinterJob();
PageFormat preformat = pjob.defaultPage();
preformat.setOrientation(PageFormat.PORTRAIT);
PageFormat postformat = pjob.pageDialog(preformat);
if (preformat != postformat) {
RepairBill r=new RepairBill();
r.setVisible(false);
pjob.setPrintable(new Printer(r.r), postformat); //r.r is the object for JPanel
if (pjob.printDialog()) {
try {
pjob.print();
} catch (PrinterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
});
コードプリンタクラス用
public static class Printer implements Printable {
final Component comp;
public Printer(Component comp) {
this.comp = comp;
}
@Override
public int print(Graphics g, PageFormat format, int page_index) throws PrinterException {
if (page_index > 0) {
return Printable.NO_SUCH_PAGE;
}
// get the bounds of the component
Dimension dim = comp.getSize();
double cHeight = dim.getHeight();
double cWidth = dim.getWidth();
// get the bounds of the printable area
double pHeight = format.getImageableHeight();
double pWidth = format.getImageableWidth();
double pXStart = format.getImageableX();
double pYStart = format.getImageableY();
double xRatio = pWidth/cWidth;
double yRatio = pHeight/cHeight;
Graphics2D g2 = (Graphics2D) g;
g2.translate(pXStart, pYStart);
g2.scale(xRatio, yRatio);
comp.paint(g2);
return Printable.PAGE_EXISTS;
}
}
plz see the screenshot of my output
コードの中心( 'translate')と' scale's(比例していません!)。単位が1/72インチの場合、絶対マージンを設定できますが、少なくともgetImageableX/Yである必要があります。 Math.min(xRatio、yRation)の両方の向きでスケールします。 –
申し訳ありませんJavaでの印刷について十分なアイデアはありません。あなたは教えてください、私はこのコードで何を変えるべきですか? – user6172452
私はそれをプログラムしました。あなたが見るように大きな違いはありません。 –