I am trying to use Java with PDFBox to draw some text to a PDF file, and set a background color for the text. I know how to draw text and draw filled rectangles, but when I try to draw text in the same position as a rectangle, the text is never shown. Example:
//draw rectangle
content.setNonStrokingColor(200, 200, 200); //gray background
content.fillRect(cursorX, cursorY, 100, 50);
//draw text
content.setNonStrokingColor(0, 0, 0); //black text
content.beginText();
content.setFont(family, fontPt);
content.moveTextPositionByAmount(cursorX, cursorY);
content.drawString("Test Data");
content.endText();
The text never shows up. It is always covered by the rectangle. Any ideas for how to make the text draw on top of the rectangle?
EDIT: As Mkl mentioned in answer, the code I provided actually works. My problem ended up being that the code was in a loop, drawing the background for each line, but the background was drawing over the previous line, and not the current line, overwriting previous text. I just needed to alter the order of events in my looping. Should this question be deleted? It seems unlikely that anyone else would find it useful.
The code you show works.
I made it runnable like this:
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDPageContentStream content = new PDPageContentStream(document, page);
PDFont font = PDType1Font.HELVETICA_BOLD;
int cursorX = 70;
int cursorY = 500;
//draw rectangle
content.setNonStrokingColor(200, 200, 200); //gray background
content.fillRect(cursorX, cursorY, 100, 50);
//draw text
content.setNonStrokingColor(0, 0, 0); //black text
content.beginText();
content.setFont(font, 12);
content.moveTextPositionByAmount(cursorX, cursorY);
content.drawString("Test Data");
content.endText();
content.close();
document.save(new File("textOnBackground.pdf"));
document.close();
(DrawOnBackground.java)
And the result looks like this:
Thus, the cause for your issue lies beyond the code you provided.
PS: I use PDFBox 1.8.10.
Related
I'm trying to capture a specific part of my screen and save it as a JPG image.
This is what I've tried thus far:
Robot r = new Robot();
// It saves screenshot to desired path
String path = "Health_Bar.JPG";
// Used to get ScreenSize and capture image
//Dimension dim = new Dimension(376, 54, 58, 18);
Rectangle capture =
new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage Image = r.createScreenCapture( new Rectangle(191, 229, 473, 150) );//r.createScreenCapture(capture);
ImageIO.write(Image, "jpg", new File(path));
System.out.println("Screenshot saved");
This code is not working as expected. I expect the x and y coordinate to be the top left corner coordinate of the image captured. And even though this is true in some cases i.e. if x,y=0; it is not in most other cases i.e x=191, y=229, as in the example code above.
For the example code above this is the out I get output image from code. However this is the image I expect to get Image of expected output. The coordinates in image 2 (expected output image) is the coordinate for the top left corner of the "Mofiki's Coordinate Finder" window.
Can anyone explain whats going on and how to fix it?
PdfContentByte canvas = writer.getDirectContent();
Rectangle rect = new Rectangle(0, 805, 594, 820);
rect.setBorder(Rectangle.BOX);
rect.setBorderWidth(1);
rect.setBackgroundColor(BaseColor.GRAY);
rect.setBorderColor(BaseColor.GREEN);
ColumnText ct = new ColumnText(canvas);
ct.setSimpleColumn(rect);
Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,Font.BOLD);
ct.addElement(new Paragraph("Your Text Goes here!! ",catFont));
ct.go();
canvas.rectangle(rect);
document.newPage();
document.close();
This is my code, here I'm trying to add text in rectangle. It didn't work! the rectangle is created but the text is not dispalyed anywhere on the pdf page.
There are a couple of issues with your code causing the text not to show.
Firstly, you add the rectangle to the canvas AFTER you add the text. The gray background will go over any text that was drawn, hiding it.
Secondly, your font size is too big for column boundary, so no text is shown.
You can make your rectangle larger and the text will show or decrease the size of your font.
For example, the following should work as I have increased the rectangle height and moved the canvas.rectangle() call to before the ColumnText.go():
Rectangle rect = new Rectangle(0, 780, 494, 820);
rect.setBorder(Rectangle.BOX);
rect.setBorderWidth(1);
rect.setBackgroundColor(BaseColor.GRAY);
rect.setBorderColor(BaseColor.GREEN);
canvas.rectangle(rect);
ColumnText ct = new ColumnText(canvas);
ct.setSimpleColumn(rect);
Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
ct.addElement(new Paragraph("Your Text Goes here!! ", catFont));
ct.go();
http://www.robinswebsitestudio.com/ButtonSamples/buttons.html
The following code does write to a premade image. The resulting image, though, has significant problems.
the original png file is a 3D button with Index Transparency and a matte so that the gif file would
blend in with the page background color
the resulting gif file is flat, the matte is gone, and the text doesn’t look smooth. The resulting
file is therefore is not something you would get from Adobe Photoshop or Fireworks and doesn’t look
professional.
If anyone has suggestions, I’m all ears. Is it impossible to get a high quality 3D button using Java?
String pathToWeb = getServletContext().getRealPath(File.separator);
File f = new File(pathToWeb + "activities.png");
BufferedImage bufferedImage = ImageIO.read(f);
// Create a graphics which can be used to draw into the buffered image
Graphics2D g2d = bufferedImage.createGraphics();
g2d.setFont(new Font( "Arial", Font.BOLD, 15 ));
//create a string with black
g2d.setColor(Color.black);
g2d.drawString("Activities", 40, 40);
// Disposes of this graphics context and releases any system resources that it is using.
g2d.dispose();
// Save as gif
File file = new File("myactivities.gif");
ImageIO.write(bufferedImage, "gif", file);
I'm in the process of making a captcha in Java but I'm having trouble improving the text quality the "drawString" method generates on top of my image.
Example of the text quality:
You can actually see the horrible edges on the text.
Java code:
File file = new File("C:\\captcha.png");
File file2 = new File("C:\\captcha2.png");
File fontfile = new File("C:\\xerox.ttf");
BufferedImage bfimage = ImageIO.read(file);
Graphics2D g = bfimage.createGraphics();
Font myfont = Font.createFont(Font.PLAIN, fontfile);
myfont = myfont.deriveFont(50f);
g.setFont(myfont);
g.setColor(Color.black);
AffineTransform att = new AffineTransform();
g.translate(100, 50);
att.rotate(Math.toRadians(15), 100, 50);
g.setTransform(att);
g.drawString("12345", 100, 50);
RenderedImage rimg = bfimage;
ImageIO.write(rimg, "PNG", file2);
Example of same font used in php, but here the quality is A LOT better with smooth edges:
How do I improve the text quality generated by the "drawString" method in Java?
Graphics and Graphics2D provide a rendering hint framework that allows you to configure some parts of the rendering of a component. Use an antialiasing rendering hint:
g2d.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);
and you should get antialiased text on your captcha.
http://docs.oracle.com/javase/6/docs/api/java/awt/RenderingHints.html for reference
I would like to draw lines and polygons with transparent lines in PDFBox. Here is some sample code of how I am drawing a blue line, but I cannot figure out to change the alpha value of the color.
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.setStrokingColor(66, 177, 230);
contentStream.drawLine(100, 100, 200, 200);
As of PDFBox 2.0 appendRawCommands is deprecated.
float alpha = 0.5f;
PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
graphicsState.setStrokingAlphaConstant(alpha);
stream.setGraphicsStateParameters(graphicsState);
// draw line here
You can achieve this by using a custom extended graphics state:
PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
graphicsState.setStrokingAlphaConstant(0.5f);
COSName graphicsStateName = page.getResources().add(graphicsState);
try (PDPageContentStream cs = new PDPageContentStream(document, page, true, true, true)) {
cs.appendRawCommands("/" + graphicsStateName.getName() + " gs\n");
// draw your line here.
}
You cannot use the alpha value of the java.awt.Color as PDFBox only uses the RGB value. As per javadoc of public void setStrokingColor(Color color) it just:
Set the stroking color, specified as
RGB.
One option could be that you set the background color as the stroking color to make your line invisible.
NOTE - Invisible != Transparent (so you won't get the see through effect)