I'm using ItextPdf 5.
How I can add special characters to my document via PdfContentByte ?
there is my code :
public void addFlag(PdfWriter writer, BaseFont baseFont, Font font) {
String mytext = "My flag : \u2691";
PdfContentByte cb = writer.getDirectContent();
cb.setFontAndSize(baseFont, font.getSize());
cb.beginText();
cb.showTextAligned(Element.ALIGN_LEFT, mytext, 10, 50, 0f);
cb.endText();
cb.stroke();
}
Related
I want to print two Jfree charts in the same document using iTextPdf, when I tried using this code, the following JFreeChart overwrite the previous one. As a result I got the second chart on both of two pages of the pdf.
public void ExportChart(OutputStream out, int width, int height) throws IOException, DocumentException {
Rectangle rect = new com.itextpdf.text.Rectangle((float) width, (float) height+130);
Document document = new com.itextpdf.text.Document(rect);
PdfWriter writer = null;
writer=PdfWriter.getInstance(document, out);
document.open();
document.add(addHeaderInfo(width));
DefaultFontMapper mapper = new DefaultFontMapper();
FontFactory.registerDirectories();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2d = tp.createGraphics(width, height, mapper);
tp.setWidth(width);
tp.setHeight(height);
//barStat is a JFreeChart Objecct
barStat.draw(g2d, new java.awt.Rectangle(width, height));
cb.addTemplate(tp, 0, 0);
document.newPage();
SingleHistogramDialog singleHD=new SingleHistogramDialog();
JFreeChart barStat2=singleHD.Histogram();
document.add(addHeaderInfo(width));
FontFactory.registerDirectories();
tp.setWidth(width);
tp.setHeight(height);
barStat2.draw(g2d, new java.awt.Rectangle(width, height));
g2d.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
}
I copied your code literally, and I made a couple of changes:
public void ExportChart(OutputStream out, int width, int height) throws IOException, DocumentException {
Rectangle rect = new com.itextpdf.text.Rectangle((float) width, (float) height+130);
Document document = new com.itextpdf.text.Document(rect);
PdfWriter writer = null;
writer=PdfWriter.getInstance(document, out);
document.open();
document.add(addHeaderInfo(width));
DefaultFontMapper mapper = new DefaultFontMapper();
FontFactory.registerDirectories();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2d = tp.createGraphics(width, height, mapper);
//barStat is a JFreeChart Objecct
barStat.draw(g2d, new java.awt.Rectangle(width, height));
cb.addTemplate(tp, 0, 0);
document.newPage();
SingleHistogramDialog singleHD=new SingleHistogramDialog();
JFreeChart barStat2=singleHD.Histogram();
document.add(addHeaderInfo(width));
tp = cb.createTemplate(width, height);
g2d = tp.createGraphics(width, height, mapper);
barStat2.draw(g2d, new java.awt.Rectangle(width, height));
g2d.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
}
I solved my problem by changing my above code this way
public void ExportChart(OutputStream out, int width, int height) throws
IOException, DocumentException {
Rectangle rect = new com.itextpdf.text.Rectangle((float) width, (float)
height+130);
Document document = new com.itextpdf.text.Document(rect);
PdfWriter writer = null;
writer=PdfWriter.getInstance(document, out);
document.open();
document.add(addHeaderInfo(width));
DefaultFontMapper mapper = new DefaultFontMapper();
FontFactory.registerDirectories();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2d = tp.createGraphics(width, height, mapper);
tp.setWidth(width);
tp.setHeight(height);
barStat.draw(g2d, new java.awt.Rectangle(width, height));
Histogram singleHD=new Histogram();
JFreeChart barStat2=singleHD.Histogram();
PdfTemplate tp2 = cb.createTemplate(width, height);
Graphics2D g2d2 = tp2.createGraphics(width, height, mapper);
tp2.setWidth(width);
tp2.setHeight(height);
barStat2.draw(g2d2, new java.awt.Rectangle(width, height));
g2d.dispose();
cb.addTemplate(tp, 0, 0);
document.newPage();
document.add(addHeaderInfo(width));
g2d2.dispose();
cb.addTemplate(tp2, 0, 0);
document.close();
}
I have a landscaped form lay on a top half of A4 page, I want it to be rotated and enlarge to a portrait layout size fill up the A4 then saved before it is faxed out. Otherwise, the fax service program will fax it out with only partial info. Here is my attempt, result is the same as the input pdf. This is my first day on programming using iText, all the google not getting me what I want. Please let me know if you can help. Thanks,
public class CopeALandscapePdfFiletoPortraitPdfFile {
//public static final String SRC = "resources/pdfs/landscapeForm.pdf";
public static final String SRC = "resources/pdfs/potraitForm.pdf";
public static final String DEST = "results/stamper/portraitFormAfterCopy.pdf";
public static void main(String[] args) throws IOException, DocumentException
{
copyPdf();
}
private static void copyPdf() throws IOException, DocumentException
{
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST));
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfReader reader = new PdfReader(SRC);
document.newPage();
int n = reader.getNumberOfPages();
PdfDictionary page;
PdfNumber rotate;
for (int p = 1; p <= n; p++) {
page = reader.getPageN(p);
rotate = page.getAsNumber(PdfName.ROTATE);
if (rotate == null) {
page.put(PdfName.ROTATE, new PdfNumber(90));
} else {
page.put(PdfName.ROTATE, new PdfNumber((rotate.intValue() + 90) % 360));
}
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(DEST));
stamper.close();
PdfImportedPage ipage = writer.getImportedPage(stamper.getReader(), 1);
cb.addTemplate(ipage, 0, 0);
document.close();
}
}
As you want to enlarge the PDF anyways, I would put enlarging and rotating into one afine transformation. Thus:
PdfReader reader = new PdfReader(SOURCE);
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, RESULT);
document.open();
double sqrt2 = Math.sqrt(2);
Rectangle pageSize = reader.getPageSize(1);
PdfImportedPage importedPage = writer.getImportedPage(reader, 1);
writer.getDirectContent().addTemplate(importedPage, 0, sqrt2, -sqrt2, 0, pageSize.getTop() * sqrt2, -pageSize.getLeft() * sqrt2);
document.close();
(EnlargePagePart.java)
E.g. for this page
it generates
Is it possible to edit width of PdfTemplate object before close of document ?
In my pdf process I create a document, and set a template for write total page number. I set width but it doesnot works :
// onOpenDocument
PdfTemplate pageNumTemplate = writer.getDirectContent().createTemplate(10, 20);
globalDataMap.put("myTemplate", pageNumTemplate)
// onCloseDocument
Font font = (Font) globalDataMap.get("myFont");
String pagenum = String.valueOf(writer.getPageNumber());
float widthPoint = font.getBaseFont().getWidthPoint(pagenum, font.getSize());
PdfTemplate pdfTemplate = (PdfTemplate) globalDataMap.get("myTemplate");
pdfTemplate.setWidth(widthPoint);
ColumnText.showTextAligned(pdfTemplate, Element.ALIGN_LEFT, new Phrase(pagenum), 0, 1, 0);
An error in the OP's initial code
You call ColumnText.showTextAligned with a String as third parameter:
String pagenum = String.valueOf(writer.getPageNumber());
[...]
ColumnText.showTextAligned(pdfTemplate, Element.ALIGN_LEFT, pagenum, 0, 1, 0);
But all ColumnText.showTextAligned overloads expect a Phrase there:
public static void showTextAligned(final PdfContentByte canvas, final int alignment, final Phrase phrase, final float x, final float y, final float rotation)
public static void showTextAligned(final PdfContentByte canvas, int alignment, final Phrase phrase, final float x, final float y, final float rotation, final int runDirection, final int arabicOptions)
(at least up to the current 5.5.9-SNAPSHOT development version).
Thus, you might want to use
ColumnText.showTextAligned(pdfTemplate, Element.ALIGN_LEFT, new Phrase(pagenum), 0, 1, 0);
instead.
But now it works
Based on the OP's code I built this proof-of-concept:
try ( FileOutputStream stream = new FileOutputStream(new File(RESULT_FOLDER, "dynamicTemplateWidths.pdf")) )
{
Document document = new Document(PageSize.A6);
PdfWriter writer = PdfWriter.getInstance(document, stream);
writer.setPageEvent(new PdfPageEventHelper()
{
PdfTemplate dynamicTemplate = null;
Font font = new Font(BaseFont.createFont(), 12);
String postfix = "0123456789";
#Override
public void onOpenDocument(PdfWriter writer, Document document)
{
super.onOpenDocument(writer, document);
dynamicTemplate = writer.getDirectContent().createTemplate(10, 20);
}
#Override
public void onEndPage(PdfWriter writer, Document document)
{
writer.getDirectContent().addTemplate(dynamicTemplate, 100, 300);
}
#Override
public void onCloseDocument(PdfWriter writer, Document document)
{
float widthPoint = font.getBaseFont().getWidthPoint(postfix, font.getSize());
dynamicTemplate.setWidth(widthPoint / 2.0f);
ColumnText.showTextAligned(dynamicTemplate, Element.ALIGN_LEFT, new Phrase(String.valueOf(writer.getPageNumber()) + "-" + postfix), 0, 1, 0);
}
});
document.open();
document.add(new Paragraph("PAGE 1"));
document.newPage();
document.add(new Paragraph("PAGE 2"));
document.close();
}
The output:
Considering I set the template width to half the width of the postfix 0123456789 in onCloseDocument, this is exactly as expected.
When I tried to write an image on Text Field, the image is written behind text. It is working for normal text and image but not on Form Fields. I want to write image on Text that covers text behind.
void OldMethod()
{
string path = #"C:\Users\";
string OutLocation = path + "New.pdf";
string Old = path + "Old.pdf";
PdfReader reader1 = new PdfReader(Old);
using (FileStream fs = new FileStream(OutLocation, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (PdfStamper stamper = new PdfStamper(reader1, fs))
{
int pageCount1 = reader1.NumberOfPages;
//Create a new layer
for (int i = 1; i <= pageCount1; i++)
{
iTextSharp.text.Rectangle rect = reader1.GetPageSize(i);
PdfContentByte cb = stamper.GetOverContent(i);
AcroFields Fields = stamper.AcroFields;
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50);
Fields.SetField("Price", #"1323423345");
Fields.SetFieldProperty("Price", "TEXTCOLOR", BaseColor.RED, null);
string Img = path + "red_slash.jpg";
iTextSharp.text.Image jpeg = Image.GetInstance(System.Drawing.Image.FromFile(Img), ImageFormat.Jpeg);
float width = 100;
float height = 200;
jpeg.ScaleToFit(width, height);
jpeg.SetAbsolutePosition(210, 315);
cb.AddImage(jpeg);
}
}
}
}
Here I need to write the image on the field "Price"
I want to add an image to a pdf file. the position of the image should be just above the last line in a pdf file.
How do I get the x,y position of the last line in the pdf or the x,y position of the end of the last text block.
Look for an object named TextMarginFinder and use it like is done in this Java example: ShowTextMargins
public void addMarginRectangle(String src, String dest)
throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
TextMarginFinder finder;
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
finder = parser.processContent(i, new TextMarginFinder());
PdfContentByte cb = stamper.getOverContent(i);
cb.rectangle(finder.getLlx(), finder.getLly(),
finder.getWidth(), finder.getHeight());
cb.stroke();
}
stamper.close();
reader.close();
}