My problem is when I try to add the content in the pdf, my table appears from the beginning and not below the header, my table with content has an incorrect height
The code is something long and I can not upload images, but I have a header and footer with pagination
It looks like it's just adding a space to my table with content but I do not know how to do it, I think my problem is in the summary method
private void addHeader(PdfWriter writer) {
PdfPTable tableHeader = new PdfPTable(2);
try {
// set default
tableHeader.setWidths(new int[] { 2, 24 });
tableHeader.setTotalWidth(527);
tableHeader.setLockedWidth(true);
tableHeader.getDefaultCell().setFixedHeight(40);
tableHeader.getDefaultCell().setBorder(Rectangle.BOTTOM);
tableHeader.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);
// addImage
Image img = Image.getInstance(getClass().getClassLoader().getResource("imgPDF/logo.png"));
tableHeader.addCell(img);
// addText
PdfPCell text = new PdfPCell();
text.setPaddingBottom(15);
text.setPaddingLeft(10);
text.setBorder(Rectangle.BOTTOM);
text.setBorderColor(BaseColor.LIGHT_GRAY);
text.addElement(new Phrase(cve.getId(), new Font(Font.FontFamily.HELVETICA, 13)));
text.addElement(new Phrase("https://myapp.com", new Font(Font.FontFamily.HELVETICA, 10)));
tableHeader.addCell(text);
// write content
tableHeader.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent());
} catch (DocumentException e) {
throw new ExceptionConverter(e);
} catch (MalformedURLException e) {
throw new ExceptionConverter(e);
} catch (IOException e) {
throw new ExceptionConverter(e);
}
private void summary() throws IOException, DocumentException {
PdfPTable table = new PdfPTable(2);
table.setHeaderRows(0);
table.setWidthPercentage(100);
table.setSpacingBefore(15);
table.setTotalWidth(100);
// Add headers
table.addCell(createHeaderCellWithColor("Summary"));
table.addCell(createHeaderCellWithColor("ACCESS"));
table.addCell(createCell("row 1"));
table.addCell(createCell("row 2"));
table.addCell(createCell("row 3"));
PdfPTable table3 = new PdfPTable(3);
PdfPCell cell = new PdfPCell(new Phrase("aaa"));
cell.setColspan(3);
table3.addCell(cell);
table.addCell(createHeaderCellWithColor("IMPACT"));
document.add(table);
With this I largely resolve,
document = new Document (PageSize.A4, 36, 36, 90, 36);
Although I would like to download more content, and that is not so close to the header
Previously had this method with a parameter equal to 15, making the content below the header, this more separate ,,, simply equals the fill
solved with
text.setPaddingBottom(8);
Related
I need to add the total page count to a PDF/A-2 document created using iText in Java. The following code is being used:
public class HeaderFooterPageEvent extends PdfPageEventHelper {
Font fontHEADER = null;
/** The template with the total number of pages. */
PdfTemplate total;
public HeaderFooterPageEvent() {
try {
fontHEADER = new Font(BaseFont.createFont("OpenSans-Regular.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 8, Font.BOLD);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onOpenDocument(PdfWriter writer, Document document) {
total = writer.getDirectContent().createTemplate(30, 16);
super.onOpenDocument(writer, document);
}
#Override
public void onCloseDocument(PdfWriter writer, Document document) {
PdfContentByte cb = writer.getDirectContent();
ColumnText.showTextAligned(total, Element.ALIGN_RIGHT,
new Phrase(String.valueOf(writer.getPageNumber() - 1)),fontHEADER),
document.right() - document.rightMargin()+5,
document.bottom() - 10, 0);
super.onCloseDocument(writer, document);
}
}
And when creating the PDF the following code is called:
Document document = new Document(PageSize.A4, 15, 15, 30, 20);
PdfAWriter writer = PdfAWriter.getInstance(document, new FileOutputStream(dest), PdfAConformanceLevel.PDF_A_2A);
writer.createXmpMetadata();
writer.setTagged();
// add header and footer
HeaderFooterPageEvent event = new HeaderFooterPageEvent();
writer.setPageEvent(event);
document.open();
document.addLanguage("en-us");
File file = new File("sRGB_CS_profile.icm");
ICC_Profile icc = ICC_Profile
.getInstance(new FileInputStream(file));
writer.setOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
Paragraph p=new Paragraph("Page 1 content",fontEmbedded); //setting an embedded font
p.setSpacingBefore(30f);
document.add(p);
document.newPage();
document.add(new Paragraph("Content of next page goes here",fontEmbedded));
document.close();
Now when we add content on 2 pages and use document.newPage() to add the new page, runtime exception is generated The page 3 was requested but the document has only 2 pages. What is a solution to this problem?
I'm using ItextPdf 5.
I have an SVG file with specifical font (integrated in svg).
When I print my SVG (using batik 1.8) the graphic is print on my document, but fonts are blocked, so, can't select them.
see below my java code :
public class ItextPdfSmallTests {
#Test
public void svgFontsTest() throws IOException, DocumentException, URISyntaxException {
String RESULT = "C:\\test\\svgFontsTest.pdf";
Document document = new Document(PageSize.A4, 36, 36, 54, 36);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
document.open();
document.add(new Paragraph("SVG Example"));
int width = 250;
int height = 250;
PdfContentByte cb = writer.getDirectContent();
PdfTemplate template = cb.createTemplate(width, height);
PdfPrinterGraphics2D g2 = new PdfPrinterGraphics2D(cb, width, height, new MyFontMapper(), PrinterJob.getPrinterJob());
PrintTranscoder prm = new PrintTranscoder();
URI svgFileURI = getClass().getResource("myfont.svg").toURI();
TranscoderInput ti = new TranscoderInput(svgFileURI.toString());
prm.transcode(ti, null);
PageFormat pg = new PageFormat();
Paper pp = new Paper();
pp.setSize(width, height);
pp.setImageableArea(0, 0, width, height);
pg.setPaper(pp);
prm.print(g2, pg, 0);
g2.dispose();
ImgTemplate img = new ImgTemplate(template);
document.add(img);
document.close();
}
class MyFontMapper extends DefaultFontMapper {
#Override
public BaseFont awtToPdf(java.awt.Font font) {
try {
return BaseFont.createFont("AmaticSC-Regular.ttf", BaseFont.WINANSI, false);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
is it possible make it editable ?
thanks for your helps
I have a requirement to generated the PDF using itext in java
Need to generate the table with 3 rows and 2 columns , able to create the table.
Country Langugage
USA English
Canada French
When I was trying to read the pdf VIA NVDA Desktop App , the table is not reading the cells properly , say when I want to focus the pointer on Canada , it should the Country - Canada
Following is the code
public class Test {
public static final String CSS = "tr { text-align: center; } th { background-color: lightgreen; padding: 3px; } td {background-color: lightblue; padding: 3px; }";
public static void main(String sunil[])
{
String pFileName = "Test.pdf";
String pFilePath = "C:/local/home/dna/pushlive/" + pFileName;
try {
FileOutputStream baosPDF = new FileOutputStream(pFilePath);
com.itextpdf.text.Rectangle pageSize = new com.itextpdf.text.Rectangle(1836, 2376);
com.itextpdf.text.Document document = new com.itextpdf.text.Document(pageSize, 36, 36, 36, 36);
PdfWriter writer = PdfWriter.getInstance(document, baosPDF);
writer.setTagged();
document.open();
PdfPTable bannerTable = new PdfPTable(4);
document.add(createFirstTable());
document.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static PdfPTable createFirstTable() {
// a table with three columns
PdfPTable table = new PdfPTable(2);
// the cell object
PdfPCell cell;
// we add a cell with colspan 3
//create header cell for first row
// now we add a cell with rowspan 2
//add metadata for each cell in the body.
// we add the four remaining cells with addCell()
cell = new PdfPCell(new Phrase("Country"));
table.addCell(cell);
cell = new PdfPCell(new Phrase("Language"));
table.addCell(cell);
cell = new PdfPCell(new Phrase("USA"));
table.addCell(cell);
cell = new PdfPCell(new Phrase("English"));
table.addCell(cell);
cell = new PdfPCell(new Phrase("Canada"));
table.addCell(cell);
cell = new PdfPCell(new Phrase("French"));
table.addCell(cell);
//set header row for the table
table.setHeaderRows(1);
return table;
}
I have a pdf, but beyond the current page, there is content that is not being displayed. I want to change the pagesize so that all of the content can be displayed. Is there a way to do this with itext?
public PdfReader changePDFPageSize(String inpdf,String outpdf,float vertical,float horizontal)
{
try
{
PdfReader reader = new PdfReader(inpdf);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outpdf));
for (int curPageNum = 1; curPageNum <= reader.getNumberOfPages(); ++curPageNum) {
PdfDictionary pagedict = reader.getPageN(curPageNum);
PdfArray mediabox = pagedict.getAsArray(PdfName.MEDIABOX);
mediabox.set(0, new PdfNumber(mediabox.getAsNumber(0).intValue()-horizontal));//left add
mediabox.set(1, new PdfNumber(mediabox.getAsNumber(1).intValue()-vertical));//down
mediabox.set(2, new PdfNumber(mediabox.getAsNumber(2).intValue()+horizontal));//right
mediabox.set(3, new PdfNumber(mediabox.getAsNumber(3).intValue()+vertical));//up
}
stamper.close();
return new PdfReader(outpdf);
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (DocumentException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
itextsharp VB.NET
Dim objReader As PdfReader
Dim objStream As FileStream
Dim objStamper As PdfStamper
Dim objContent As PdfContentByte
Dim objImport As PdfImportedPage
Dim objMark As Image
objReader = New PdfReader(strBookPath)
objStream = New FileStream(strTempPath, FileMode.Create)
objStamper = New PdfStamper(objReader, objStream)
objContent = objStamper.GetOverContent(1)
objImport = objStamper.GetImportedPage(objReader, 1)
objContent.AddTemplate(objImport, PageSize.A4.Width / objImport.Width, 0, 0, PageSize.A4.Height / objImport.Height, 0, 0)
objReader.GetPageN(1).Put(PdfName.CROPBOX, New PdfRectangle(PageSize.A4.Width, PageSize.A4.Height))
objReader.GetPageN(1).Put(PdfName.MEDIABOX, New PdfRectangle(PageSize.A4.Width, PageSize.A4.Height))
I'am using itextPDF APIs in my project.The scenario is to add a few paragraphs and then followed by an image and then agian a series of text.
say: For n number of times
1.TEXT CONTENT
2.IMAGE
3.TEXT CONTENT
I added #1 TEXT CONTENT,#2.IMAGE and #3 to a Paragraph,and then to document.
I tried with two images a small and one big(which will reqire one page to render on pdf)
The small one worked fine, but when tried to add a bigger image the above sequence was not in order.
The text which was added after the image started appearing before the mage and the image slipped on to the next page.This is because the image needs one
whole page so went on to next page,but the text which was below image crept on current page which is not expected.
I tried using adding Paragraph to a Chapter, which worked but always diaplayed the chapter number.When I set chapter.setTriggerNewPage(false) the same
behaviour as detailed above was seen.
I have attached both the source, can I request you to help me in getting this issue resolved.
1. Using Paragraph
public Test3() {
// TODO Auto-generated constructor stub
}
public static Image getImageFromResource(String URI){
Image image = null;
try {
image = Image.getInstance(URI);
} catch (BadElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return image;
}
public static void main(String[] args) {
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
try {
PdfWriter.getInstance(document , new FileOutputStream("D:\\test\\TestPage.pdf"));
document.open();
Paragraph p = new Paragraph();
p.add("TEXT EXPECTED BEFORE IMAGE ");
Paragraph p1 = new Paragraph();
Image image = getImageFromResource("D:\\test\\Test.jpg");
p1.add(image);
Paragraph p2 = new Paragraph();
p2.add("TEXT EXPECTED AFTER IMAGE ");
document.add(p2);
document.add(p1);
document.add(p);
} catch(DocumentException de) {
System.err.println(de.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
document.close();
}
2.Using Chapter
public Test3() {
// TODO Auto-generated constructor stub
}
public static Image getImageFromResource(String URI){
Image image = null;
try {
image = Image.getInstance(URI);
} catch (BadElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return image;
}
public static void main(String[] args) {
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
try {
PdfWriter.getInstance(document , new FileOutputStream("D:\\test\\TestPage.pdf"));
document.open();
Paragraph p = new Paragraph();
p.add("TEXT EXPECTED BEFORE IMAGE ");
Paragraph p1 = new Paragraph();
Image image = getImageFromResource("D:\\test\\Test.jpg");
p1.add(image);
Paragraph p2 = new Paragraph();
p2.add("TEXT EXPECTED AFTER IMAGE ");
for(int i=0;i<10;i++){
Chapter chapter1 = new Chapter(p, 1);
Chapter chapter2 = new Chapter(p1, 2);
Chapter chapter3 = new Chapter(p2, 3);
document.add(chapter1);
document.add(chapter2);
document.add(chapter3);
}
} catch(DocumentException de) {
System.err.println(de.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
document.close();
}
Thanks in advance,
Kiran
Are you wanting the image to be rendered on a page itself? One solution is to use document.next() to insert a page break before and/or after the image. You can also try wrapping all 3 of your elements into another object such as a Phrases and Chunks in IText.
Add this line before the writer declaration:
writer.setStrictImageSequence(true);
I used to have the same problem. I solved them with this line.
I found the solution here: iText - Insert image into PDF
Documentation: API