I work with the last version of itextPdf. And all used to work fine I don't know when it has begun to trouble.
I have that method to converts to pdf a GraphePinScene object.
public void toPdf(Scene scene, float clipWidth, float clipHeight, String path)
{
float pageWidth = (float) scene.getView().getWidth();
float pageHeight = (float) scene.getView().getHeight();
double xScale = 1.0;
double yScale = 1.0;
Document d = new Document();
PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(new File(path)));
d.open();
PdfContentByte cb = writer.getDirectContent();
//scaling
if (pageWidth > PDF_MAX_WIDTH) {
xScale = (double) (pageWidth / PDF_MAX_WIDTH);
pageWidth = PDF_MAX_WIDTH;
}
if (pageHeight > PDF_MAX_HEIGHT) {
xScale = (double) (pageHeight / PDF_MAX_HEIGHT);
pageHeight = PDF_MAX_HEIGHT;
}
Graphics2D g2d = new PdfGraphics2D(cb, pageWidth + clipWidth, pageHeight + clipHeight);
g2d.scale(xScale, yScale);
scene.paint(g2d);
g2d.dispose();
d.close();
}
And the scene object contains some Widgets. All widgets are included in the pdf only the ones that are created with GradientPaint are not imaged in the pdf file, this is one of the widgets:
public final class SecondaryStationWidget extends IconNodeWidget {
//Staff
#Override
protected void paintWidget() {
Graphics2D g = getGraphics();
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
rh.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHints(rh);
g.setPaint(new GradientPaint(44, 29, new Color(154, 191, 239), 88, 58, new Color(17, 74, 148), true));
g.fill(new RoundRectangle2D.Double(1, 2,
88,
58,
10, 10));
}
}
The probleme has been resolved by changing (forcing) the background of those kind of widgets (in the constructor).
setBackground(new Color(0, 0, 0, 1)); //Remove
setBackground(Color.WHITE); //Add
Related
In above code i want to use custom font (which is commented on code), when i use commented font1 then iam not getting output properly.
BufferedImage source = ImageIO.read(input_file);
File backImg = new File("C:\\Users\\saradhi\\Desktop\\water-lily-3784022__340.jpg");
BufferedImage backImgB = ImageIO.read(backImg);
final BufferedImage textImage = new BufferedImage(
backImgB.getWidth(),
backImgB.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = textImage.createGraphics();
FontRenderContext frc = g.getFontRenderContext();
/*
* Font font1 = Font.createFont(Font.TRUETYPE_FONT, new
* File("C:\\Users\\saradhi\\Desktop\\Pacifico.ttf")); font1.deriveFont(9f);
*/
Font font = new Font(Font.SANS_SERIF, Font.BOLD, 120);
GlyphVector gv = font.createGlyphVector(frc, name);
Rectangle2D box = gv.getVisualBounds();
int xOff = 25 + (int) - box.getX();
int yOff = 80 + (int) - box.getY();
Shape shape = gv.getOutline(xOff, yOff);
g.setClip(shape);
g.drawImage(backImgB, 0, 0, null);
g.setClip(null);
g.setStroke(new BasicStroke(2 f));
g.setColor(Color.BLACK);
g.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.draw(shape);
g.dispose();
File file = new File("cat-text.png");
ImageIO.write(textImage, "png", new File("C:\\Users\\saradhi\\Desktop\\resultEX.jpeg"));
i get the custom font through this code
Font font = Font.createFont(Font.TRUETYPE_FONT, new File("C:\\Pacifico.ttf"))
.deriveFont(48 f);
I'm trying write some mechanism to creating mems. After the image is painted with text, the text quality is very low. I dont know what I'm doing wrong. Here is my following draw method:
private BufferedImage generateImage(File file) throws IOException {
Image image = ImageIO.read(file);
final int imgWidth = image.getWidth(null);
final int imgHeight = image.getHeight(null);
int labelHeight = (imgHeight / 2);
int labelWidth = (imgWidth - 25);
int xMargin = ((imgWidth - labelWidth) / 2);
int yMargin = (imgHeight - (labelHeight + 10));
Font font = new Font("Arial Black", Font.BOLD, 42);
String upperText = this.doggle.getUppertext().toUpperCase();
String bottomText = this.doggle.getBottomtext().toUpperCase();
ImagePanel background = new ImagePanel(image);
background.setSize(imgWidth, imgHeight);
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String absoluteDiskPath = servletContext.getRealPath("/resources/images/logo.png");
BufferedImage imageLogo = ImageIO.read(new File(absoluteDiskPath));
ImageIcon icon = new ImageIcon(imageLogo);
JLabel imageLogoPanel = new JLabel ();
imageLogoPanel.setIcon(icon);
imageLogoPanel.setSize(imageLogo.getWidth(), imageLogo.getHeight());
imageLogoPanel.setVerticalAlignment(SwingConstants.BOTTOM);
JLabel textUpper = new JLabel();
textUpper.setText(upperText);
textUpper.setVerticalAlignment(SwingConstants.TOP);
textUpper.setSize(labelWidth, labelHeight);
textUpper.setPreferredSize(new Dimension(labelWidth, (imgHeight / 2)));
textUpper.setFont(font);
textUpper.setForeground(Color.decode("#" + this.doggle.getUppercolor()));
JLabel textUpperShadow = new JLabel(upperText, JLabel.CENTER);
textUpperShadow.setVerticalAlignment(SwingConstants.TOP);
textUpperShadow.setSize(labelWidth, labelHeight);
textUpperShadow.setPreferredSize(new Dimension(labelWidth, (imgHeight / 2)));
textUpperShadow.setFont(font);
textUpperShadow.setForeground(Color.BLACK);
JLabel textLower = new JLabel(bottomText, JLabel.CENTER);
textLower.setVerticalAlignment(SwingConstants.BOTTOM);
textLower.setSize(labelWidth, labelHeight);
textLower.setPreferredSize(new Dimension(labelWidth, (imgHeight / 2)));
textLower.setFont(font);
textLower.setForeground(Color.decode("#" + this.doggle.getBottomcolor()));
JLabel textLowerShadow = new JLabel(bottomText, JLabel.CENTER);
textLowerShadow.setVerticalAlignment(SwingConstants.BOTTOM);
textLowerShadow.setSize(labelWidth, labelHeight);
textLowerShadow.setPreferredSize(new Dimension(labelWidth, (imgHeight / 2)));
textLowerShadow.setFont(font);
textLowerShadow.setForeground(Color.BLACK);
background.add(textUpper);
background.add(textUpperShadow);
background.add(textLower);
background.add(textLowerShadow);
background.add(imageLogoPanel);
textUpper.setLocation(xMargin, 5);
textUpperShadow.setLocation((xMargin + 2), 7);
textLower.setLocation(xMargin, yMargin - 16);
textLowerShadow.setLocation((xMargin + 2), ((yMargin - 16) + 2));
imageLogoPanel.setLocation((xMargin - 5), ((yMargin * 2) - 8));
BufferedImage img = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
background.printAll(g2d);
g2d.dispose();
return img;
}
And here is a some part of the image (The text at the top is the actual text and bottom text is what it should look like)
What can I do to improve the visual quality of my text? I Will be grateful for help.
I am using itext liberary for pdf generation in mine JavaFX project.Now i want's to print hindi , punjabi text from database inside report , How can i do this. However IText library is not recognise hindi and punjabi unicode ???
here is mine code
out = new ByteArrayOutputStream();
try {
// initialize document with page size and margins
document = new Document(PageSize.A4, 60, 40, 60, 60);
this.setAlignmentOfCompanyInfo(Common.comp
.getReportsHeaderAlignment());
writer = PdfWriter.getInstance(document, out);
writer.setPageEvent(new PageEventForAddressBookReport());
document.open();PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(w, h);
#SuppressWarnings("deprecation")
Graphics2D g2 = tp.createGraphicsShapes(w, h);
g2.drawString("वर्तमान शेष", 200, 100);
g2.dispose();
g2.setColor(Color.GREEN);
cb.addTemplate(tp, 50, 400);
BufferedImage bi = new BufferedImage(100, 20, BufferedImage.TYPE_INT_ARGB);
Graphics2D ig2 = bi.createGraphics();
ImageIO.write(bi, "PNG", new File("ourImageName.PNG"));
Image image = Image.getInstance(tp);
document.add(new Chunk(image,5,5));
document.close();
As itext is not supporting vernacular language, convert text to bitmap and set as image. Use below method for conversion:
public Bitmap textAsBitmap(String text, float textSize, float stroke,
int color) {
TextPaint paint = new TextPaint();
paint.setTextSize(textSize);
paint.setAntiAlias(true);
// paint.setTextAlign(Paint.Align.LEFT);
paint.setAntiAlias(true);
paint.setColor(color);
// paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(20f);
paint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
float baseline = (int) (-paint.ascent() + 3f); // ascent() is negative
StaticLayout staticLayout = new StaticLayout(text, 0, text.length(),
paint, 435, android.text.Layout.Alignment.ALIGN_NORMAL, 1.0f,
1.0f, false);
// int linecount = staticLayout.getLineCount();
//
// int height = (int) (baseline + paint.descent() + 3) * linecount + 10;
Bitmap image = Bitmap.createBitmap(staticLayout.getWidth(),
staticLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(image);
// canvas.drawARGB(100, 100, 100, 100);
staticLayout.draw(canvas);
return image;
}
It's never a good idea to add the text in a notation that isn't Unicode, but that's not the main problem. The main problem is that you aren't providing the right font. You need a font that knows how to draw Indic glyphs. Arial Unicode MS is such a font:
String text = "\u0936\u093e\u0902\u0924\u093f";
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(100, 50);
Graphics2D g2 = tp.createGraphicsShapes(100, 50);
java.awt.Font font = new java.awt.Font(
"Arial Unicode MS", java.awt.Font.PLAIN, 12);
g2.setFont(font);
g2.drawString("Graphics2D: " + text, 0, 40);
g2.dispose();
cb.addTemplate(tp, 36, 750);
Note that this assumes that Java has access to the font arialuni.ttf.
i am using hindi text to be appear in PDf as below
BaseFont unicode = BaseFont.createFont("/home/mani/Documents/Back up (works)/Devanagari/Devanagari.ttf",
BaseFont.COURIER, BaseFont.EMBEDDED);
Font font=new Font(unicode,12,Font.NORMAL,new BaseColor(50,205,50));
table = new PdfPTable(new float[] { 10, 60, 30 });
table.setWidthPercentage(100);
PdfPCell customerLblCell = new PdfPCell(new Phrase("karent balance",
font));
Its working fine in mine case .
I was looking for a way to rearrange several arguments recived as strings and one byte[] image and put them all togther as one image (jpg for example) ready to be printed (immidiatly).
example:
public static void printCard(String name, String LName, Image MainImage)
Basicly this function will be a simple card printer.
I was looking for an idea or some one who can guide me, this could be very easy if some one will guide me a bit.
This is a simple method that I use to add text onto a pre-existing image.
I'm sure you can work out how to pass a blank image in and add the other lines as you see fit.
private BufferedImage drawText2(BufferedImage bi, String outputText) {
Graphics2D g2d = bi.createGraphics();
g2d.setFont(new Font("Helvetica", Font.BOLD, 36));
FontMetrics fm = g2d.getFontMetrics();
int textWidth = fm.stringWidth(outputText);
int imageWidth = bi.getWidth();
int leftAlignment;
int topAlignment;
// Align the text to the middle
leftAlignment = (imageWidth / 2) - (textWidth / 2);
// Align the text to the top
topAlignment = fm.getHeight() - 10;
// Create the drop shadow
g2d.setColor(Color.DARK_GRAY);
g2d.drawString(outputText, leftAlignment + 2, topAlignment + 2);
// Create the text itself
g2d.setColor(Color.LIGHT_GRAY);
g2d.drawString(outputText, leftAlignment, topAlignment);
g2d.dispose();
return bi;
}
If you want to print directly from your application you can use
java.awt.print package.
Try this method
public static void printCard(final String name, final String lName, final Image mainImage){
Printable contentToPrint = new Printable(){
#Override
public int print(Graphics graphics, PageFormat pageFormat, int page) throws PrinterException {
if (page > 0) {
return NO_SUCH_PAGE;
}
pageFormat.setOrientation(PageFormat.PORTRAIT);
graphics.drawImage(mainImage, 0, 0, null);
graphics.drawString(lName, 100, 300);
graphics.drawString(name, 100, 100);
return PAGE_EXISTS;
}
};
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(contentToPrint);
//You can show a print dialog before printing by job by wrapping the following blocks with a conditional statement if(job.printDialog()){...}
try {
job.print();
} catch (PrinterException e) {
System.err.println(e.getMessage());
}
}
You need to import the print related classes from java.awt.print.
i used graphics2d to impliment my function . this method recive 2 images and 6 strings :
Bufferdimage bi is my blank image, on this image i add objects (ex: image, string) :
private static BufferedImage drawText2(BufferedImage logo,BufferedImage small,BufferedImage bi, String Headline,String outputText2,String outputText3,String outputText4,String outputText5,String outputText6) {
Graphics2D g2d = bi.createGraphics();
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
g2d.setRenderingHints(rh);
g2d.setFont(new Font("Arial", Font.BOLD, 50));
FontMetrics fm = g2d.getFontMetrics();
int textWidth = fm.stringWidth(Headline);
int imageWidth = bi.getWidth();
int leftAlignment;
int topAlignment;
// Align the text to the top
topAlignment = fm.getHeight() - 10;
// Create the text itself
//headline
leftAlignment = (imageWidth / 2) - (textWidth);
g2d.setColor(Color.blue);
g2d.drawString(Headline, leftAlignment+290, topAlignment+60);
//property changed
g2d.setFont(new Font("Arial", Font.BOLD, 30));
fm = g2d.getFontMetrics();
textWidth = fm.stringWidth(Headline);
//second line
textWidth = fm.stringWidth(outputText2);
leftAlignment = (imageWidth / 2) - (textWidth);
g2d.setColor(Color.black);
g2d.drawString(outputText2, leftAlignment+290, topAlignment+120);
//third line
textWidth = fm.stringWidth(outputText3);
leftAlignment = (imageWidth / 2) - (textWidth);
g2d.setColor(Color.black);
g2d.drawString(outputText3, leftAlignment+290, topAlignment+160);
//4 line
textWidth = fm.stringWidth(outputText4);
leftAlignment = (imageWidth / 2) - (textWidth);
g2d.setColor(Color.black);
g2d.drawString(outputText4, leftAlignment+290, topAlignment+200);
//5 line
textWidth = fm.stringWidth(outputText5);
leftAlignment = (imageWidth / 2) - (textWidth);
g2d.setColor(Color.black);
g2d.drawString(outputText5, leftAlignment+290, topAlignment+240);
//property changed
g2d.setFont(new Font("Arial", Font.getFont("Arial").HANGING_BASELINE, 20));
fm = g2d.getFontMetrics();
//security line
textWidth = fm.stringWidth(outputText6);
leftAlignment = (textWidth);
g2d.setColor(Color.red);
g2d.drawString(outputText6, 10, topAlignment+300);
//logo
g2d.drawImage (logo, 44, 44,180,70, null);
//profile
g2d.drawImage (small, 60, 120,160,190, null);
g2d.dispose();
return bi;
}
bi is the card with all other objects
btw i added smothing to the font, without this the text is very unpleasent.
When I add 1 chart to the document there is no problem
When I add the second chart I get this error ...
Exception in thread "main" com.itextpdf.text.exceptions.IllegalPdfSyntaxException: Unbalanced save/restore state operators.
chart1 = SpecialJFreeChartBuilder.createChart1(
"Site and Number of Requests ", results);
document.newPage();
PdfContentByte Add_Chart_Content = writer.getDirectContent();
PdfTemplate template_Chart_Holder = Add_Chart_Content
.createTemplate(width, height);
Graphics2D Graphics_Chart = template_Chart_Holder.createGraphics(
width, height, new DefaultFontMapper());
Rectangle2D Chart_Region = new Rectangle2D.Double(0, 0, 540, 380);
chart1.draw(Graphics_Chart, Chart_Region);
Graphics_Chart.dispose();
Add_Chart_Content.addTemplate(template_Chart_Holder, 0, 0);
chart2 = SpecialJFreeChartBuilder.createChart2(
"Site and totalAmount ", results);
document.newPage();
PdfContentByte Add_Chart_Content1 = writer.getDirectContent();
PdfTemplate template_Chart_Holder1 = Add_Chart_Content1
.createTemplate(width, height);
Graphics2D Graphics_Chart1 = template_Chart_Holder1.createGraphics(
width, height, new DefaultFontMapper());
Rectangle2D Chart_Region1 = new Rectangle2D.Double(0, 0, 540, 380);
chart2.draw(Graphics_Chart1, Chart_Region1);
Graphics_Chart.dispose();
Add_Chart_Content.addTemplate(template_Chart_Holder1, 0, 0);
....
document.close();
Can anyone help me ....
Solved the issue ... Graphics_Chart.dispose(); must be : Graphics_Chart1.dispose(); Graphics_Chart2.dispose();