java print api - printing JComponent at 300dpi - java

please tell me if I am doing something wrong. I want to print barcodes onto labels, so I need high quality printout for these barcodes so I am pushing printer to print in 300dpi. What I've done:
made a big JFrame; width: 2490px, height: 3515px so it represents A4 paper in 1:1 measure (this is A4 paper resolution if print is to be 300dpi)
draw 40 barcode images onto contentPane of that JFrame
setup print attributes so it will print in 300dpi:
PrintRequestAttributeSet aset =
new HashPrintRequestAttributeSet();
PrinterResolution pr =
new PrinterResolution(300,300,PrinterResolution.DPI);
MediaPrintableArea mpa=new MediaPrintableArea(8,21,
210-16, 296-42, MediaPrintableArea.MM);
attribute set is filled with this data:
aset.add( mpa );
aset.add( pr );
aset.add( MediaSizeName.ISO_A4 );
aset.add( new Copies(1) );
aset.add(OrientationRequested.PORTRAIT );
aset.add(PrintQuality.HIGH);
aset.add( Fidelity.FIDELITY_TRUE );
printJob.setPrintable(this);
printJob.print(aset);
this class has print method:
public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(),pageFormat.getImageableY());
disableDoubleBuffering(componentToBePrinted);
componentToBePrinted.paint(g2d);
enableDoubleBuffering(componentToBePrinted);
return(PAGE_EXISTS);
}
I need to have 40 barcodes on that A4 sheet, each in size 48.5mm x 25.4mm.
What is printed out on paper is 6 barcodes each doubled in size of 104mm x 46mm (that is in width almost half of page's width) which fulfilled whole paper.
Any idea, what can I do wrong?

Your resolution is probably being set to 72 dpi which has the effect of increasing the size of the image.

Related

Make a button with an image

In fact, I've managed to do that BUT i get a problem that can be easily seen in the following image:
As you can see, there's a border between the image "jugar" and the final of the button. All I want to do is to remove that, so only the background image and the button "jugar" are seen. Here's my code:
public final class GUI extends Application {
#Override
public void start(final Stage primaryStage) throws InterruptedException, FileNotFoundException {
primaryStage.setTitle("CARCASSONE");
StackPane layout = new StackPane();
ImageView jugar = new ImageView(new Image(new FileInputStream("JUGAR.png")));
final Button openButton = new Button(null, jugar);
openButton.;
layout.getChildren().add(openButton);
BackgroundImage bI = new BackgroundImage(new Image(new FileInputStream("CARCASSONE.png")), null, null, null, null);
layout.setBackground(new Background(bI));
openButton.setOnAction(
new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
jugarPartida(primaryStage);
}
});
Scene inici = new Scene(layout, 610, 900);
primaryStage.setScene(inici);
primaryStage.show();
}
I must use JavaFX, so jbutton can't be used.
Any idea to solve that? Just want to remove that annoying border.
The problem with a transparent background is that there’s still an invisible rectangular area that responds to mouse clicks.
You can set the button’s region shape and its clip to a shape that matches your image bounds, so the Button effectively does not exist outside of those bounds:
openButton.setStyle("-fx-padding: 0;");
SVGPath shape = new SVGPath();
shape.setContent("M 18 0 "
+ "H 251 C 265 0 277 7 277 25 "
+ "V 52 C 277 69 265 76 251 76 "
+ "H 18 C 12 76 0 69 0 52 "
+ "V 25 C 0 7 12 0 18 0 "
+ "z");
shape.setFill(Color.BLACK);
openButton.setShape(shape);
openButton.setClip(shape);
Quick SVG path tutorial:
M means moveto (start drawing at that position)
H means draw horizontal line to the specified X position
V means draw vertical line to the specified Y position
C means curveto (draw Bézier curve using specified control points; last coordinate pair is the curve’s final endpoint)
z means close the shape
What you can do is apply css to set the color of openbutton to something like rgba(255, 255, 255, 0.00). You can also do this directly in code.
Something like String style = "-fx-background-color: rgba(255, 255, 255, 0.00);";
openButton.setStyle(style);
The last 0.0 is will make it transparent.

Apache PDFBox Renders Straight Line Crooked in PNG

I have a PDF that when I render it to a png it renders a line crooked, or rather with a step in it. This is the PDF and what it should look like: https://drive.google.com/file/d/1E-zucbreD7pVwWc3Z4MNe_lzsP6D9m49/view
Here is the full PNG rendering using PDFBox 2.0.13 and openjdk version 1.8.0_181:
And here is the specific portion of the PNG that has the step:
Excerpt of the page content stream:
q
1 0 0 1 35.761 450.003 cm
0 i
0.75 w
0 0 m
50.923 0 l
S
Q
q
1 0 0 1 86.139 450 cm
0 i
0.75 w
0 0 m
14.9 0 l
S
Q
("cm" is an affine transform, "m" a moveto, "l" a lineto). One can see that the two lines are slightly different, one at 450.003, the other one at 450.
Here's some code that simulates the error by replicating what PDFBox is doing:
BufferedImage bim = new BufferedImage(612, 792, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) bim.getGraphics();
RenderingHints r = new RenderingHints(null);
r.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
r.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
r.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.addRenderingHints(r);
g.translate(0, 792);
g.scale(1, -1);
g.setStroke(new BasicStroke(0.75f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10));
g.setColor(Color.black);
GeneralPath path = new GeneralPath();
path.moveTo(35.761f, 450.003f);
path.lineTo(35.761f + 50.923f, 450.003f);
g.draw(path);
path = new GeneralPath();
path.moveTo(86.139f, 450f);
path.lineTo(86.139f + 14.9f, 450f);
g.draw(path);
g.dispose();
ImageIO.write(bim, "png", new File("...."));
One can get rid of the error by commenting this line:
r.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
This could be done in the source code of PDFBox, or by passing the renderingHints in PDFRenderer.setRenderingHints(). However that one isn't available now, but will be available in 2.0.14 (see issue PDFBOX-4435, try a snapshot). And you can expect the rendering to be of poor quality by not having anti aliasing.
Update:
instead of removing the line mentioned above, add this one:
r.put(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
Source.

WPrinterJob.validatePaper() is changing original imageableArea of page when I click on properties button of Print dialog and after print it

I am printing Legal size paper, when I print it without open properties dialog then it is printing properly, but when I click on "Properties" button for confirm page type (no matter I am clicking on "OK" or "Cancel" then Paper imageableArea is become changed while job.print(attributeSet)
Dialog with Properties Button
Expected Height/Width:612/1008
Actual Height/Width:612/792 (setting in WPrinterJob.validatePaper())
Printing page with issue
Here is my code,
private void preparePageFormat(PageFormat pf)
{
Paper ppr = new Paper();
pf.setOrientation(PageFormat.LANDSCAPE);
MediaSizeName msn = MediaSizeName.NA_LEGAL;
MediaSize msz = MediaSize.getMediaSizeForName(msn);
double inch = 72.0;
width = msz.getX(MediaSize.INCH) * inch;
height = msz.getY(MediaSize.INCH) * inch;
ppr.setSize(a4Width, a4Height);
ppr.setImageableArea(0, 0, a4Width, a4Height);
pf.setPaper(ppr);
}
main()
{
PrinterJob job = PrinterJob.getPrinterJob();
PageFormat pageFormat = job.defaultPage();
preparePageFormat(pageFormat);
job.setPrintable(previewPanel.getPrintable(), pageFormat);
PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet();
attributeSet.add(OrientationRequested.LANDSCAPE);
attributeSet.add(MediaSizeName.NA_LEGAL);
if (job.printDialog(attributeSet))
{
attributeSet.add(new MediaPrintableArea((float)pageFormat.getImageableX(),(float)pageFormat.getImageableY(),
(float)pageFormat.getImageableWidth(),(float)pageFormat.getImageableHeight(),MediaPrintableArea.INCH));
job.print(attributeSet);
}
}
For this printer issue, you need to confirm setting from Printer Properties .
Verify all settings are matching with your Page Type.
And verfiy here too.

Wrong allignment when drawing a JTextPane into a BufferedImage

I am trying to draw some styled text into a buffered image. I use a JTextPane which is not part of any view hierarchy. I set the document properties with the desired alignment but the results are not correctly aligned. Even worse, I would get different results for different font size or sometimes even different results when running the same test again.
The following image shows the results. The paragraphs should be be, top to bottom, aligned left, center, right, full. The red frame is the JTextPane border. See for your self.
Because I am a new stackoverflow user, it did not allow me to post an image. You can see the image at http://www.sendtoprint.net/preview/textfile.jpg
This was done on Java 1.7 but did also happen in 1.6. The code:
public void createBufferedImage ()
{
try
{
BufferedImage bi = new BufferedImage (1000, 1200, BufferedImage.TYPE_INT_RGB);
Graphics2D gg = bi.createGraphics ();
gg.setRenderingHint (RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
gg.setRenderingHint (RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
gg.setBackground (Color.white);
gg.fillRect (0, 0, bi.getWidth (), bi.getHeight ());
gg.scale (3.0f, 3.0f);
gg.translate (16, 16);
String text = "The residents of Colorado and Washington state have voted to legalize "
+ "the recreational use of marijuana, and all hell is about to break "
+ "loose -- at least ideologically. The problem is that pot is still very much "
+ "illegal under federal law, and the Obama administration must decide whether "
+ "to enforce federal law in a state that has rejected the substance of that law."
+ "\n\n";
DefaultStyledDocument doc = new DefaultStyledDocument ();
MutableAttributeSet attr = new SimpleAttributeSet ();
StyleConstants.setFontFamily (attr, "Arial");
StyleConstants.setFontSize (attr, 9);
StyleConstants.setForeground (attr, Color.black);
MutableAttributeSet parAttr = new SimpleAttributeSet ();
doc.insertString (0, text, attr);
StyleConstants.setAlignment (parAttr, StyleConstants.ALIGN_LEFT);
doc.setParagraphAttributes (0, doc.getLength (), parAttr, false);
doc.insertString (doc.getLength (), text, attr);
StyleConstants.setAlignment (parAttr, StyleConstants.ALIGN_CENTER);
doc.setParagraphAttributes (doc.getLength () - text.length (), text.length (), parAttr, false);
doc.insertString (doc.getLength (), text, attr);
StyleConstants.setAlignment (parAttr, StyleConstants.ALIGN_RIGHT);
doc.setParagraphAttributes (doc.getLength () - text.length (), text.length (), parAttr, false);
doc.insertString (doc.getLength (), text, attr);
StyleConstants.setAlignment (parAttr, StyleConstants.ALIGN_JUSTIFIED);
doc.setParagraphAttributes (doc.getLength () - text.length (), text.length (), parAttr, false);
JTextPane tc = new JTextPane ();
tc.setBorder (BorderFactory.createLineBorder (Color.red, 1));
tc.setDocument (doc);
tc.setBackground (Color.white);
tc.setLocation (0, 0);
tc.setSize (new Dimension (300, 370));
tc.paint (gg);
System.out.println ("Writing file: " + new Date ().toString ());
File file = new File ("C:\\Users\\Yishai\\Desktop\\text\\file.jpg");
ImageIO.write (bi, "jpg", file);
}
catch (Exception e)
{
System.out.println (e.getMessage ());
}
}
Any ideas what can I do differently? is there a JTextPane setting? A text cache? anything?
Thanks.

Java A3 printing on Macs coming out at A4 scale

I have an odd problem that seems to be specific to Mac computers. I have a prog that prints the content of an AWT drawing surface to an A3 sheet of paper. On Linux and windows machines the output is OK. Printing from a Mac I get the same dialog with the same preset parameters, the printer prints on an A3 sheet of paper as expected, but for some reason the image is scaled to fit an A4 area. Below are the relevant sections of code:
public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
PageFormat format = new PageFormat();
format.setOrientation(PageFormat.LANDSCAPE);
double margin = 18; // quarter inch
double m2 = margin * 2;
Paper paper = format.getPaper();
paper.setSize(16.54 * 72, 11.69 * 72); // A3 Landscape
paper.setImageableArea(margin, margin, paper.getWidth()-m2, paper.getHeight()-m2);
format.setPaper(paper);
printJob.setPrintable(this, format);
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
attributes.add(MediaSizeName.ISO_A3);
attributes.add(OrientationRequested.LANDSCAPE);
attributes.add(new MediaPrintableArea((int)margin, (int)margin,
(int)(paper.getWidth()-m2), (int)(paper.getHeight()-m2),
MediaPrintableArea.INCH));
if(printJob.printDialog(attributes) ){
try {
printJob.print(attributes);
} catch(PrinterException pe) {
pe.printStackTrace();
}
}
}
public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
if(this.componentToBePrinted instanceof PlannerView){
setScale(g2d);
}
disableDoubleBuffering(componentToBePrinted);
componentToBePrinted.paint(g2d);
enableDoubleBuffering(componentToBePrinted);
return(PAGE_EXISTS);
}
}
public void setScale(Graphics2D g2d){
PlannerView planner = (PlannerView)this.componentToBePrinted;
planner.resetZoom();
double scale = 1.0 / planner.getRowLength();
scale *= 4.0;
g2d.scale(scale, scale);
}
Does anyone know what could be causing this?
Cheers.
Try calling
PageFormat newFormat =printJob.pageDialog(format);
before printing, the printer may modify the margins.
At least take a look in the debugger and see what it turns into.
Also note that the Macintosh native printing coordinate systems for landscape is inverted.
So maybe try it with REVERSE_LANDSCAPE instead of LANDSCAPE ( and it might be flipped, but may not get list in translation)
Deal with setImageableArea(), change the values and try. Also apply reverse_landscape for mac.
And set the A3 size: 1190 & 842 not decimal values.

Categories