How to position a PDFGraphis2D object in iText? - java

I'm creating a PDF and somewhere in there I want to add a JPanel.
Using PdfContentByte and PdfGraphics2D I am able to add it to the document but:
How do I position it so it's at the left margin instead of the left page edge?
How do I prevent it from showing up over other elements?
In other words: how can I put it in a Paragraph?
Code fragment:
// multiple Paragraphs
// ...
JPanel myPanel = ...
PdfContentByte canvas = writer.getDirectContent();
int origWidth = myPanel.getWidth();
int origHeight = myPanel.getHeight();
float width = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
double scale = width / origWidth;
Graphics2D g2 = new PdfGraphics2D(canvas, origWidth, origHeight);
g2.scale(scale, scale);
myPanel.paint(g2);
g2.dispose();
// even more Paragraphs
//...

I got it working by using a PdfTemplate and creating an Image from that.
PdfContentByte canvas = writer.getDirectContent();
int origWidth = myPanel.getWidth();
int origHeight = myPanel.getHeight();
PdfTemplate template = canvas.createTemplate(origWidth, origHeight);
Graphics2D g2 = new PdfGraphics2D(template, origWidth, origHeight);
myPanel.paint(g2);
g2.dispose();
Image image = Image.getInstance(template);
float width = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
image.scaleToFit(width, 1000);
document.add(image)

Related

Rotate text using pdfbox

I'm trying to rotate text using pdfbox by I couldn't achieve it. I tried to set the texMatrix but my text is not rotating as intended.
Does someone have an idea of how I could turn at 90 degrees my text?
This is my code :
contentStream.beginText();
float tx = titleWidth / 2;
float ty = titleHeight / 2;
contentStream.setTextMatrix(Matrix.getTranslateInstance(tx, ty));
contentStream.setTextMatrix(Matrix.getRotateInstance(Math.toRadians(90),tx,ty));
contentStream.setTextMatrix(Matrix.getTranslateInstance(-tx, -ty));
contentStream.newLineAtOffset(xPos, yPos);
contentStream.setFont(font, fontSize);
contentStream.showText("Tets");
contentStream.endText();
Thank You
Here's a solution that draws three pages, one with text unrotated, one with text rotated but keeping the coordinates as if planning landscape printing, and one that is what you wanted (rotated around the center of the text). My solution is close to that, it rotates around the bottom of the center of the text.
public static void main(String[] args) throws IOException
{
PDDocument doc = new PDDocument();
PDPage page1 = new PDPage();
doc.addPage(page1);
PDPage page2 = new PDPage();
doc.addPage(page2);
PDPage page3 = new PDPage();
doc.addPage(page3);
PDFont font = PDType1Font.HELVETICA;
float fontSize = 20;
int xPos = 100;
int yPos = 400;
float titleWidth = font.getStringWidth("Tets") / 1000;
float titleHeight = fontSize;
float tx = titleWidth / 2;
float ty = titleHeight / 2;
try (PDPageContentStream contentStream = new PDPageContentStream(doc, page1))
{
contentStream.beginText();
contentStream.newLineAtOffset(xPos, yPos);
contentStream.setFont(font, fontSize);
contentStream.showText("Tets");
contentStream.endText();
}
// classic case of rotated page
try (PDPageContentStream contentStream = new PDPageContentStream(doc, page2))
{
contentStream.beginText();
Matrix matrix = Matrix.getRotateInstance(Math.toRadians(90), 0, 0);
matrix.translate(0, -page2.getMediaBox().getWidth());
contentStream.setTextMatrix(matrix);
contentStream.newLineAtOffset(xPos, yPos);
contentStream.setFont(font, fontSize);
contentStream.showText("Tets");
contentStream.endText();
}
// rotation around text
try (PDPageContentStream contentStream = new PDPageContentStream(doc, page3))
{
contentStream.beginText();
Matrix matrix = Matrix.getRotateInstance(Math.toRadians(90), 0, 0);
matrix.translate(0, -page3.getMediaBox().getWidth());
contentStream.setTextMatrix(matrix);
contentStream.newLineAtOffset(yPos - titleWidth / 2 - fontSize, page3.getMediaBox().getWidth() - xPos - titleWidth / 2 - fontSize);
contentStream.setFont(font, fontSize);
contentStream.showText("Tets");
contentStream.endText();
}
doc.save("saved.pdf");
doc.close();
}
This example rotates around the left baseline of the text and uses the matrix translation to position the text at the specific point.
The showText() is always positioned at 0,0, which is the position before the rotation. The matrix translation then positions the text after the rotation.
If you want another rotation point of your text relocation the text rotation position in the contentStream.newLineAtOffset(0, 0)-line
float angle = 35;
double radians = Math.toRadians(angle);
for (int x : new int[] {50,85,125, 200})
for (int y : new int[] {40, 95, 160, 300}) {
contentStream.beginText();
// Notice the post rotation position
Matrix matrix = Matrix.getRotateInstance(radians,x,y);
contentStream.setTextMatrix(matrix);
// Notice the pre rotation position
contentStream.newLineAtOffset(0, 0);
contentStream.showText(".(" + x + "," + y + ")");
contentStream.endText();
}
To get the height and the width of the text you want to rotate use font.getBoundingBox().getHeight()/1000*fontSize and font.getStringWidth(text)/1000*fontSize.

Itext7 - vertical aligment PdfFormField

Is there a way to edit vertica aligment of the text written in a PdfFormField.
The default seems to be center, I need a bottom.
With normal setValue the text is written at the center. I tried with rectangle/canvas but did not work (here the code)
PdfPage page = form.getField(key).getWidgets().get(0).getPage();
PdfCanvas pdfCanvas = new PdfCanvas(page);
PdfArray position = formFields.get(key).getWidgets().get(0).getRectangle();
double x = position.getAsNumber(0).getValue();
double y = position.getAsNumber(1).getValue();
double xWidth = position.getAsNumber(2).getValue();
double yWidth = position.getAsNumber(3).getValue();
Rectangle rectangle = new Rectangle((float) x, (float) y, (float) xWidth, (float) yWidth);
Canvas canvas = new Canvas(pdfCanvas, pdfDoc, rectangle);
Paragraph paragraph = new Paragraph(valore);
paragraph.setFont(font);
paragraph.setVerticalAlignment(VerticalAlignment.BOTTOM);
canvas.add(paragraph);

How can I create a non-square BufferedImage from a non-square image file?

I'm trying to create a BufferedImage from an arbitrary image file and then center that image in the background of a JPanel. I don't have any problems with square images, but I can't figure out how to handle non-square images.
Some debugging indicates that the (immediate) problem is that when I use ImageIO to create a BufferedImage from a rectangular input file, say one that's 256x128, BufferedImage.getHeight() returns 256 rather than 128.
Here's a snippet approximating my code:
class ExtendedPanel extends JPanel {
static final int WIDTH = 400;
static final int HEIGHT = 400;
BufferedImage image;
public ExtendedPanel(File f) {
super();
setPreferredSize(new Dimension(WIDTH,HEIGHT));
image = ImageIO.read(f);
}
#Override
public void paintComponent(Graphics g) {
int x = (WIDTH - image.getWidth())/2;
int y = (HEIGHT - image.getHeight())/2;
Graphics2D g2d = (Graphics2d)g;
g2d.drawRenderedImage(image,AffineTransform.getTranslateInstance(x,y));
}
}
As I said, this is fine for square image files. But with rectangular images that are wider than they are tall, the image is displayed higher than it should be. I haven't tried it yet with images taller than they are wide but I'm afraid that it that case the image would be displayed too far to the left. What can I do?
It is more a problem of (understanding) the right calculation.
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2d)g;
// How to scale the image:
double xscale = ((double)WIDTH) / image.getWidth();
double yscale = ((double)HEIGHT) / image.getHeight());
// When scaling proportionally:
double scale = Math.min(xscale, yscale); // max for covering entire panel.
xscale = scale;
yscale = scale;
double w = scalex * image.getWidth();
double h = scaley * image.getHeight();
double x = (getWidth() - w) / 2;
double y = (getHeight() - h) / 2;
g.drawImage(img, (int)x, (int)y, (int)w, (int)h, Color.BLACK, null);
//g2d.translate(x, y);
//g2d.scale(xscale, yscale);
//g2d.draw...;
}
Using the simple (scaling) version of drawImage what is needed is entirely clear.
To be considered is proportionally scaling, filling entirely (loss of image part) or upto maximal size (seeing background).

Java calculate image center return minus negative results

I am trying to calculate image center(to add water marks)following - add-water-to-image and the results shows negative x, for some of the images, here is the math part:
int centerX = (sourceImage.getWidth() - (int) rect.getWidth()) / 2;
int centerY = sourceImage.getHeight() / 2;
and the entire function:
public void addTextWatermark(String text, File sourceImageFile, File destImageFile, int textSize) {
try {
BufferedImage sourceImage = ImageIO.read(sourceImageFile);
Graphics2D g2d = (Graphics2D) sourceImage.getGraphics();
// initializes necessary graphic properties
AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f);
g2d.setComposite(alphaChannel);
g2d.setColor(Color.BLACK.darker());
//Font(fontName, fontStyle, foneSize)
g2d.setFont(new java.awt.Font("Arial", Font.BOLD, textSize));
FontMetrics fontMetrics = g2d.getFontMetrics();
//text - input text , g2d - Graphics2D
Rectangle2D rect = fontMetrics.getStringBounds(text, g2d);
// calculates the coordinate where the String is painted
int centerX = (sourceImage.getWidth() - (int) rect.getWidth()) / 2;
int centerY = sourceImage.getHeight() / 2;
// paints the textual watermark
g2d.drawString(text, centerX, centerY);
ImageIO.write(sourceImage, "png", destImageFile);
g2d.dispose();
} catch (IOException ex) {
System.out.println(ex.getMessage().toString());
}
}
1-Is there a way to ensure the math will work for all images?
2-Is there a diffrence between jpg and png in this calclation?
Thanks.
edit
The image sizes that was causeing it were:
1-to big(3000*3000).
2-to small(60*60).
With textSize(g2d.setFont(new java.awt.Font("Arial", Font.BOLD, textSize));) - 32 or less.
So I found 2 ways to handle this issue:
1- if x or y are smaller then 0 I have resize the image using resize-image
2- if the watermark is to small just increase text size - g2d.setFont(new java.awt.Font("Arial", Font.BOLD, textSize));
Thanks for all the help #jon Skeet.

Customize icon in Drag Drop Event?

I am dragging and dropping the jTable cell from one jTable to another jTable.For Now it is showing me default drag drop icon.
I am using TransferHandler class to implement this.
I Override getDragImage(image) to put my customize image But it is not working.
This way i implemented my code Implementation
I tried this code into this method.
File newFile = new File("./dragImage.jpeg");
Font font = new Font("Tahoma", Font.PLAIN, 11);
FontRenderContext frc = new FontRenderContext(null, true, true);
Rectangle2D bounds = font.getStringBounds(l_value, frc);
int w = (int) bounds.getWidth();
int h = (int) bounds.getHeight();
BufferedImage image = new BufferedImage(10,10, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 10, 10);
g.setColor(Color.BLACK);
g.setFont(font);
g.drawString(l_value, (float) bounds.getX(), (float) -bounds.getY());
g.dispose();
return image;
This code is working in my main method but here in this function it is not working.

Categories

Resources