Can't generate complete data to PDF file in java - java

I have a jtable that i'm using to display some data. Say I have around 200 rows of data. I am able to generate the pdf, by using the iText library, but the problem i'm facing is that all the rows aren't generated. How can I add a new page dynamically so that I generate all the rows? Kindly have a look at the code below and please help me out here.
Document doc = new Document(new Rectangle(1350, 1450));
PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, 800, 0.50f);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = new java.util.Date();
String generatedDate = formatter.format(date);try {
PdfWriter writer;
writer = PdfWriter.getInstance(doc, new FileOutputStream(save_pdf.getSelectedFile().getAbsoluteFile() + ".pdf"));
writer.setViewerPreferences(PdfWriter.PageLayoutSinglePage);
doc.open();
PdfAction action = PdfAction.gotoLocalPage(1, pdfDest, writer);
writer.setOpenAction(action);
doc.add(new Paragraph("REPORTS", f));
doc.add(new Paragraph("Document Generated On - " + generatedDate, f));
PdfContentByte cb = writer.getDirectContent();
cb.saveState();
Graphics2D g2;
g2 = cb.createGraphics(1350, 1275);
Shape oldClip = g2.getClip();
g2.clipRect(0, 0, 1350, 1275);//1275
table1.print(g2);
JTableHeader h = table1.getTableHeader();
h.print(g2);
g2.setClip(oldClip);
writer.newPage();
g2.dispose();
cb.restoreState();
} catch (DocumentException | FileNotFoundException e) {
}
doc.close();

Okay, so this is pretty basic example...
JTable supports printing already, through it's various print methods, basically this boils down to getting an instance of the JTable Printable interface and passing it off to the print API, which needs a Graphics2D context to paint to...
Oddly enough, you have a Graphics2D context, so the trick here is to "act" as the printer and call the JTable's Printable print method yourself...
DefaultTableModel model = new DefaultTableModel(0, 10);
for (int row = 0; row < 400; row++) {
Object[] values = new Object[10];
for (int col = 0; col < 10; col++) {
values[col] = ((char) ('A' + col)) + "x" + row;
}
model.addRow(values);
}
JTable table = new JTable(model);
table.setSize(table.getPreferredSize());
JTableHeader tableHeader = table.getTableHeader();
tableHeader.setSize(tableHeader.getPreferredSize());
Document doc = new Document(new Rectangle(1350, 1450));
PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, 800, 0.50f);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date = new java.util.Date();
String generatedDate = formatter.format(date);
Paper paper = new Paper();
paper.setSize(1350, 1450);
paper.setImageableArea(10, 10, 1350 - 20, 1450 - 20);
PageFormat pf = new PageFormat();
pf.setPaper(paper);
Printable printable = table.getPrintable(JTable.PrintMode.NORMAL, null, null);
try {
PdfWriter writer;
writer = PdfWriter.getInstance(doc, new FileOutputStream("test.pdf"));
writer.setViewerPreferences(PdfWriter.PageLayoutSinglePage);
doc.open();
// Use this to "test" if there is page
// available for printing, otherwise it prints
// a empty page and I can't figure out
// how to remove it :P
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();
Font f = new Font(Font.TIMES_ROMAN, 12f);
int page = 0;
int result = Printable.NO_SUCH_PAGE;
PdfContentByte cb = writer.getDirectContent();
do {
result = printable.print(g, pf, page);
if (result == Printable.PAGE_EXISTS) {
cb.saveState();
Graphics2D g2 = cb.createGraphics(1350, 1450);
System.out.println(page);
result = printable.print(g2, pf, page);
g2.dispose();
cb.restoreState();
doc.add(new Paragraph("REPORTS", f));
doc.add(new Paragraph("Document Generated On - " + generatedDate, f));
page++;
doc.newPage();
}
} while (result == Printable.PAGE_EXISTS);
g.dispose();
} catch (DocumentException | PrinterException | FileNotFoundException e) {
e.printStackTrace();
} finally {
doc.close();
}
Now, I need to display the table in order to get the row headers to display, but there might be another work around for this.

PdfAction action = PdfAction.gotoLocalPage(1, pdfDest, writer);
Here you use only one page to write the content. So iText can not write the content in next page. gotoLocalPage method only acted in only specific page. Please refer the below link and change your code...
Just gothrough this page

Related

How to remove top padding in pdf

I am creating PDF file in my android application and printing that PDF file with my Wi-Fi printer. Below is my code for creating pdf file.
private void createPDFFile(String path) {
if (new File(path).exists())
new File(path).delete();
try {
Document document = new Document();
//save
PdfWriter.getInstance(document, new FileOutputStream(path));
//Open to write
document.open();
//setting
Rectangle pagesize = new Rectangle(612, 864);
document.setPageSize(pagesize);
document.addCreationDate();
document.addAuthor("Securevs");
document.addCreator("Moin Khan");
document.setMargins(0, 0, 0, 0);
//Font Setting
BaseColor coloAccent = new BaseColor(0, 0, 0, 68);
float fontSize = 21.0f;
float valueFontSize = 26.0f;
// Custom Font
//BaseFont fontName = BaseFont.createFont("assets/fonts/brandon_medium.otf", "UTF-8", BaseFont.EMBEDDED);
BaseFont fontName = BaseFont.createFont("assets/fonts/KohinoorDevanagari-Bold.ttf", "UTF-8", BaseFont.EMBEDDED);
//Create Title Of Doc
Font title = new Font(fontName, 40.0f, Font.BOLD, BaseColor.BLACK);
addNewItem(document, txtName.getText().toString(), Element.ALIGN_CENTER, title);
document.add(new Paragraph("\n"));
//Add more
Font orderNumberFont = new Font(fontName, fontSize, Font.BOLD, BaseColor.BLACK);
//addNewItem(document, "Order Number:", Element.ALIGN_LEFT, orderNumberFont);
BitmapDrawable drawable = (BitmapDrawable) imgUserImage.getDrawable();
Bitmap bm = drawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.scaleAbsolute(125, 174);
myImg.setAlignment(Image.LEFT);
//document.add(myImg);
BitmapDrawable drawableQR = (BitmapDrawable) imgQrCode.getDrawable();
Bitmap bmQR = drawableQR.getBitmap();
ByteArrayOutputStream streamQR = new ByteArrayOutputStream();
bmQR.compress(Bitmap.CompressFormat.JPEG, 100, streamQR);
Image myImgQR = Image.getInstance(streamQR.toByteArray());
myImgQR.scaleAbsolute(200, 200);
myImgQR.setAlignment(Image.RIGHT);
//document.add(myImgQR);
addNewImageWithLeftAndRight(document, myImg, myImgQR);
/* PdfPTable table = new PdfPTable(2);
table.setSpacingBefore(20);
table.setWidthPercentage(100);
table.setWidths(new int[]{1, 2});
table.addCell(createImageCell(myImg));
table.addCell(createImageCell(myImgQR));
document.add(table);*/
/*Font orderNumberValueFont = new Font(fontName, valueFontSize, Font.NORMAL, BaseColor.BLACK);
addNewItem(document, "#717171", Element.ALIGN_LEFT, orderNumberValueFont);
addLineSeperator(document);
addNewItem(document, "Order Date", Element.ALIGN_LEFT, orderNumberFont);
addNewItem(document, "3/8/2010", Element.ALIGN_LEFT, orderNumberValueFont);
addLineSeperator(document);*/
addNewItemCenter(document, "Visiting to : " + txtEmployeeName.getText().toString(), orderNumberFont);
addNewItemCenter(document, "Date and time : " + txtDateAndTime.getText().toString(), orderNumberFont);
addNewItemCenter(document, "Purpose of visit : " + txtPurpose.getText().toString(), orderNumberFont);
addNewItemCenter(document, "Visiting from : " + txtCompany.getText().toString(), orderNumberFont);
addNewItemWithLeftAndRight(document, "Out time:................", "................", orderNumberFont, orderNumberFont);
addNewItemWithLeftAndRight(document, "", "Signature", orderNumberFont, orderNumberFont);
//addNewItemRight(document, "Signature", orderNumberFont);
document.close();
Toast.makeText(this, "success", Toast.LENGTH_SHORT).show();
printPdf();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
My paper size is 11.2 * 9.2 CM. Now I want to shift my content little bit above. I am selecting paper size 4*6 in while printing. Please suggest how can I achieve this.
I used to do this except I would scale the image so that it was always centered if the image was small and if the image was larger I would scale it horizontally or vertically then place it in the center of the page.
This is what you need, You need to find the X and Y you want.
X and Y will be the position that will start drawing on the page
image.setAbsolutePosition(x, y)
You can refer to the code and customize it to suit your wishes.
fun createPdf () {
val rectText = Rectangle()
rectText.width = 9.5 * 72.0
rectText.height = 12 * 72.0
val doc = Document(com.itextpdf.text.Rectangle(rectText), 0f, 0f, 0f, 0f)
val image: Image = Image.getInstance(bitmap)
val scaleImage = scaleImage(doc, image)
//Scale image fit height or width
image.scalePercent(scaleImage.second)
//Find a place to start drawing pictures on the page
val absolutePosition = findPositionToPutImgIntoPage(scaleImage.first, doc, image)
image.setAbsolutePosition(absolutePosition.first,absolutePosition.second)
doc.add(image)
doc.newPage()
}
//calculate to know whether to scale the image horizontally or vertically
private fun scaleImage(doc: Document, image: Image): Pair<Boolean, Float> {
var isScaleWidth = false
val scaleWidth: Float =
(doc.pageSize.width - doc.leftMargin() - doc.rightMargin()) / image.width * 100
val scaleHeight: Float =
(doc.pageSize.height - doc.bottomMargin() - doc.topMargin()) / image.height * 100
val scale = if (scaleHeight > scaleWidth) {
isScaleWidth = true
scaleWidth
} else {
scaleHeight
}
return Pair(isScaleWidth, scale)
}
private fun findPositionToPutImgIntoPage(
isScaleWidth: Boolean,
doc: Document,
image: Image
): Pair<Float, Float> {
return if (isScaleWidth) {
val y = (doc.pageSize.height - image.scaledHeight) / 2
Pair(0f, y)
} else {
val x = (doc.pageSize.width - image.scaledWidth) / 2
Pair(x, 0f)
}
}

Add image above table - Itext

How to add an image over a table with Itext?
I'm using the version 5.5.10
implementation 'com.itextpdf:itextg:5.5.10'
Edit: The image can not be inside the row / column, it must be independent to populate any position on the screen
I'm trying to add an image over the columns of a table, but the result is this:
It always lies below the rows of the column.
To add the image I'm doing so:
public void addImg (int dwb, float x, float y, float desc) {
try{
Bitmap bitmap = dwbToBitmap(context, dwb);
ByteArrayOutputStream stream3 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream3);
Image image = Image.getInstance(stream3.toByteArray());
stream3.close();
image.scaleToFit(sizeImgFit, sizeImgFit);
image.setAbsolutePosition(35.6f + 10f + x, height-y-sizeImg-(height-desc));
document.add(image);
}catch (Exception e){
log("addImg", e);
}
}
I have already tried to change the order, create the first table and then add the images or vise versa, but it does not work.
Does anyone know how to put the images in position Z above all?
I create the table like this:
public void createTable(ArrayList<String> header, ArrayList<String[]> clients){
float height = 569/header.size();
sizeImg = height;
sizeImgFit = sizeImg - 2;
PdfPTable pdfPTable = new PdfPTable(header.size());
pdfPTable.setWidthPercentage(100);
PdfPCell pdfPCell;
int indexC = 0;
while(indexC < header.size()){
pdfPCell = new PdfPCell(new Phrase(header.get(indexC++), fHeaderText));
pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);
pdfPCell.setBackgroundColor(BaseColor.GRAY);
pdfPTable.addCell(pdfPCell);
}
int i = 0;
for(String[] row : clients){
int p = 0;
for(String linha : row){
pdfPCell = new PdfPCell(new Phrase(linha, fText));
pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);
pdfPCell.setVerticalAlignment(Element.ALIGN_CENTER);
pdfPCell.setFixedHeight(height);
pdfPTable.addCell(pdfPCell);
log("linha - coluna", i + " - " + p);
p++;
}
i++;
}
//paragraph.add(pdfPTable);
try {
document.add(pdfPTable);
}catch (Exception e){
log("paragraph", e);
}
}
These methods mentioned above are in a class:
public class TemplatePDF {
private Context context;
private File pdfFile;
private Document document;
public PdfWriter pdfWriter;
private Paragraph paragraph;
private Rotate event;
private Font fTitle = new Font(Font.FontFamily.TIMES_ROMAN, 20, Font.BOLD);
private Font fSubTitle = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
private Font fHeaderText = new Font(Font.FontFamily.TIMES_ROMAN, 3, Font.NORMAL, BaseColor.WHITE);
private Font fText = new Font(Font.FontFamily.TIMES_ROMAN, 3);
private Font fHText = new Font(Font.FontFamily.TIMES_ROMAN, 8);
private Font fHighText = new Font(Font.FontFamily.TIMES_ROMAN, 15, Font.BOLD, BaseColor.RED);
private float width = PageSize.A4.getWidth();
private float height = PageSize.A4.getHeight();
public float sizeImg;
public float sizeImgFit;
public TemplatePDF(Context context){
this.context = context;
}
public void openDocument(){
createFile();
try{
document = new Document(PageSize.A4);
pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
event = new Rotate();
document.open();
}catch (Exception e){
Log.e("erro", e.toString());
}
}
private void createFile(){
File folder = new File(Environment.getExternalStorageDirectory().toString(), "PDF");
if(!folder.exists()){
folder.mkdirs();
}
pdfFile = new File(folder, key() + ".pdf");
}
public void closeDocument(){
document.close();
}
...
}
To create PDF, I do so:
//Creating the object
TemplatePDF templatePDF = new TemplatePDF(ficha_pre.this);
templatePDF.openDocument();
templatePDF.addMetaData("Relatório", "Situs", "Woton Sampaio");
templatePDF.addTitles("Relatório", "","Data: " + getDate());
//Creating the table
ArrayList<String> header = new ArrayList<>();
for(int i = 0; i < 55; i++){
header.add(forString(i));
}
ArrayList<pdfItens> itens = arrayItens();
ArrayList<String[]> files = array();
templatePDF.createHeaderFicha(itens);
templatePDF.createTable(header, files);
//Adding image
templatePDF.addImg(R.drawable.ic_a, 0, 20, 566);
The cause for this is that an Image added to the Document is added in a virtual layer underneath that of regular text and tables. Apparently iText developers assumed that text and table elements by default are to be drawn in front of images.
But you can explicitly add the Image to a different virtual layer which is in turn above that of text and tables, in addImg you merely have to replace
document.add(image);
by
pdfWriter.getDirectContent().addImage(image);
Your image in addImg has its AbsolutePosition set. This actually is necessary for images you want to add to the DirectContent because the DirectContent has no idea about current insertion positions or page dimensions.
As an aside, there also is a DirectContentUnder for stuff that shall go even below the layer of Images added via the Document.

Create a watermark (pdf Optional Content) that shows only when printing using PDFBox

I have come across many examples that use the PDFBox Layer Utility's appendFormAsLayer method as shown below:
/**
* Places the given form over the existing content of the indicated page (like an overlay).
* The form is enveloped in a marked content section to indicate that it's part of an
* optional content group (OCG), here used as a layer. This optional group is returned and
* can be enabled and disabled through methods on {#link PDOptionalContentProperties}.
* #param targetPage the target page
* #param form the form to place
* #param transform the transformation matrix that controls the placement
* #param layerName the name for the layer/OCG to produce
* #return the optional content group that was generated for the form usage
* #throws IOException if an I/O error occurs
*/
public PDOptionalContentGroup appendFormAsLayer(PDPage targetPage,
PDXObjectForm form, AffineTransform transform,
String layerName) throws IOException
{
PDDocumentCatalog catalog = targetDoc.getDocumentCatalog();
PDOptionalContentProperties ocprops = catalog.getOCProperties();
if (ocprops == null)
{
ocprops = new PDOptionalContentProperties();
catalog.setOCProperties(ocprops);
}
if (ocprops.hasGroup(layerName))
{
throw new IllegalArgumentException("Optional group (layer) already exists: " + layerName);
}
PDOptionalContentGroup layer = new PDOptionalContentGroup(layerName);
ocprops.addGroup(layer);
PDResources resources = targetPage.findResources();
PDPropertyList props = resources.getProperties();
if (props == null)
{
props = new PDPropertyList();
resources.setProperties(props);
}
//Find first free resource name with the pattern "MC<index>"
int index = 0;
PDOptionalContentGroup ocg;
COSName resourceName;
do
{
resourceName = COSName.getPDFName("MC" + index);
ocg = props.getOptionalContentGroup(resourceName);
index++;
} while (ocg != null);
//Put mapping for our new layer/OCG
props.putMapping(resourceName, layer);
PDPageContentStream contentStream = new PDPageContentStream(
targetDoc, targetPage, true, !DEBUG);
contentStream.beginMarkedContentSequence(COSName.OC, resourceName);
contentStream.drawXObject(form, transform);
contentStream.endMarkedContentSequence();
contentStream.close();
return layer;
}
What is the significance of "MC" in the getPDFName call in the previous code?
I have written the following code to insert the watermark on each page of an existing pdf and enable each group of optional content.
LayerUtility layerUtility = new LayerUtility(document);
PDXObjectForm form = layerUtility.importPageAsForm(overlayDoc, 0);
for (int i = 0; i < document.getDocumentCatalog().getAllPages().size(); i++) {
PDPage page = (PDPage) document.getDocumentCatalog().getAllPages().get(i);
PDOptionalContentGroup ocGroup = layerUtility.appendFormAsLayer(page, form, new AffineTransform(), "watermark" + i);
}
PDOptionalContentProperties ocprops = document.getDocumentCatalog().getOCProperties();
for (String groupName : ocprops.getGroupNames()) {
if (groupName.startsWith("watermark")) {
ocprops.setGroupEnabled(groupName, true);
}
}
Setting the group to enabled or disabled "setGroupEnabled(groupName, true)" causes it to show for both displaying and printing. According to other information I have researched on this subject it is possible to more finely tune when optional content is visible, which indicates the existence of onScreen and onPrint Boolean attributes that can be set to determine the visibility of the content. See https://acrobatusers.com/tutorials/watermarking-a-pdf-with-javascript
Is there a way using PDFBox to cause a watermark to be visible when printed but not when displayed? If not, any suggestions of alternate solutions would be appreciated.
Here is additional code to create a watermark pdf from a string (createOverlay) and a function (addWatermark) that calls the LayerUtility passing the watermark document. All that is required is to create a PDDocument from any existing pdf file and pass it with the watermark string.
public PDDocument addWatermark(PDDocument document, String text) throws IOException {
PDDocument overlayDoc = createOverlay(text);
// Create the watermark in an optional content group
LayerUtility layerUtility = new LayerUtility(document);
PDXObjectForm form = layerUtility.importPageAsForm(overlayDoc, 0);
for (int i = 0; i < document.getDocumentCatalog().getAllPages().size(); i++) {
PDPage page = (PDPage) document.getDocumentCatalog().getAllPages().get(i);
layerUtility.appendFormAsLayer(page, form, new AffineTransform(), "watermark" + i);
}
return document;
}
private PDDocument createOverlay(String text) throws IOException {
// Create a document and add a page to it
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDExtendedGraphicsState extendedGraphicsState = new PDExtendedGraphicsState();
// Set the transparency/opacity
extendedGraphicsState.setNonStrokingAlphaConstant(0.4f);
if (page.findResources() == null) {
page.setResources(new PDResources());
}
PDResources resources = page.findResources();// Get the page resources.
// Get the defined graphic states.
if (resources.getGraphicsStates() == null)
{
resources.setGraphicsStates(new HashMap<String, PDExtendedGraphicsState>());
}
Map<String, PDExtendedGraphicsState> graphicsStateDictionary = resources.getGraphicsStates();
if (graphicsStateDictionary != null){
graphicsStateDictionary.put("TransparentState", extendedGraphicsState);
resources.setGraphicsStates(graphicsStateDictionary);
}
// the x/y coords
Float xVal = 0f; //Float.parseFloat(config.getProperty("ss.xVal"));
Float yVal = 0f; //Float.parseFloat(config.getProperty("ss.yVal"));
// Start a new content stream which will "hold" the to be created content
PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true);
contentStream.appendRawCommands("/TransparentState gs\n");
// Create the text and position it
contentStream.beginText();
contentStream.setFont(font, fontSize);
contentStream.setTextRotation(Math.PI/4,page.getMediaBox().getWidth()/4,page.getMediaBox().getHeight()/4);
contentStream.setNonStrokingColor(210,210,210); //light grey
contentStream.moveTextPositionByAmount(xVal, yVal);
contentStream.drawString(text);
contentStream.endText();
// Make sure that the content stream is closed:
contentStream.close();
//return the string doc
return document;
}
private void addWaterMark(PDDocument document) throws Exception
{
PDDocumentCatalog catalog = document.getDocumentCatalog();
PDOptionalContentProperties ocprops = catalog.getOCProperties();
if (ocprops == null)
{
ocprops = new PDOptionalContentProperties();
ocprops.setBaseState(BaseState.OFF);
catalog.setOCProperties(ocprops);
}
String layerName = "conWatermark";
PDOptionalContentGroup watermark = null;
if (ocprops.hasGroup(layerName))
{
watermark = ocprops.getGroup(layerName);
}
else
{
watermark = new PDOptionalContentGroup(layerName);
ocprops.addGroup(watermark);
}
COSDictionary watermarkDic = watermark.getCOSObject();
COSDictionary printState = new COSDictionary();
printState.setItem("PrintState", COSName.ON);
COSDictionary print = new COSDictionary();
print.setItem("Print", printState);
watermarkDic.setItem("Usage", print);
COSDictionary asPrint = new COSDictionary();
asPrint.setItem("Event", COSName.getPDFName("Print"));
COSArray category = new COSArray();
category.add(COSName.getPDFName("Print"));
asPrint.setItem("Category", category);
COSArray ocgs = new COSArray();
ocgs.add(watermarkDic);
asPrint.setItem(COSName.OCGS, ocgs);
COSArray as = new COSArray();
as.add(asPrint);
COSDictionary d = (COSDictionary) ((COSDictionary) ocprops.getCOSObject()).getDictionaryObject(COSName.D);
d.setItem(COSName.AS, as);
for (int n = 0; n < document.getNumberOfPages(); n++)
{
PDPage page = document.getPage(n);
PDResources resources = page.getResources();
if (resources == null)
{
resources = new PDResources();
page.setResources(resources);
}
String text1 = "Confidential";
String text2 = "Document ..."; //
PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
graphicsState.setNonStrokingAlphaConstant(0.08f);
PDPageContentStream contentStream = new PDPageContentStream(document, page, AppendMode.APPEND, true, true);
contentStream.setGraphicsStateParameters(graphicsState);
contentStream.setNonStrokingColor(Color.GRAY);
contentStream.beginMarkedContent(COSName.OC, watermark);
contentStream.beginText();
PDRectangle pageSize = page.getBBox();
float fontSize = this.getFittingFontSize(pageSize, text1);
PDFont font = this.WATERMARK_FONT;
contentStream.setFont(font, fontSize);
float text1Width = this.getTextWidth(font, fontSize, text1);
float rotation = (float) Math.atan(pageSize.getHeight() / pageSize.getWidth());
Point p = this.getStartPoint(pageSize, fontSize, text1);
AffineTransform at = new AffineTransform(1, 0, 0, 1, p.getX(), p.getY());
at.rotate(rotation);
Matrix matrix = new Matrix(at);
contentStream.setTextMatrix(matrix);
contentStream.showText(text1);
fontSize = this.getFittingFontSize(pageSize, text2);
contentStream.setFont(font, fontSize);
contentStream.newLineAtOffset(-(this.getTextWidth(font, fontSize, text2) - text1Width) / 2, -fontSize * 1.2f);
contentStream.showText(text2);
contentStream.endMarkedContent();
contentStream.endText();
contentStream.close();
}
}

how to move to the page i want in pdf file in java

i am working on generating a pdf file of multiple pages but when i am adding my information to the pdf file this information is added only in the last page and the previous pages are empty, this is a part of my code and i need to start from the first page and then move to the second according to a condition, where in every page i want only 20 rows of data.
is there any solution??
try {
Document d = new Document();
PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(pdf));
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
d.open();
PdfContentByte cb = writer.getDirectContent();
for (int currentPage = 0; currentPage < 3; ++currentPage) {
d.newPage();
PdfTemplate template = cb.createTemplate(pageWidth, pageHeight);
Graphics2D g2d = new PdfGraphics2D(template, pageWidth, pageHeight * (currentPage + 1));
d.setPageCount(currentPage + 1);
g2d.dispose();
cb.addTemplate(template, 0, 0);
}
cb.beginText();
cb.setFontAndSize(bf, 12);
cb.showTextAligned(Element.ALIGN_LEFT, "FULL NAME:", 10, 820, 0);
cb.showTextAligned(Element.ALIGN_LEFT, "Age:", 10, 810, 0);
cb.endText();
cb.eoFill();
d.close();
} catch (DocumentException | IOException | SQLException e) {
System.out.println(e);
}

Create Index File(TOC) for merged pdf using itext library in java

I am using iText to create a single PDF by merging a number of PDFs using PDFCopy. I need to create a TOC (not bookmarks) at the beginning of this document with clickable links to the first pages of each of the source PDFs.
Code to merge pdf
Document PDFJoinInJava = new Document();
PdfCopy PDFCombiner = new PdfCopy(PDFJoinInJava, outputStream);
PdfCopy.PageStamp stamp;
PDFJoinInJava.open();
PdfReader ReadInputPDF;
List<InputStream> pdfs = streamOfPDFFiles;
List<PdfReader> readers = new ArrayList<PdfReader>();
int totalPages = 0;
Iterator<InputStream> iteratorPDFs = pdfs.iterator();
for (; iteratorPDFs.hasNext(); pdfCounter++) {
InputStream pdf = iteratorPDFs.next();
PdfReader pdfReader = new PdfReader(pdf);
readers.add(pdfReader);
totalPages += pdfReader.getNumberOfPages();
pdf.close();
}
int number_of_pages;
int currentPageNumber = 0;
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
PdfImportedPage page;
// Loop through the PDF files and add to the output.
int count = 1;
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
count++;
number_of_pages = pdfReader.getNumberOfPages();
// Create a new page in the target for each source page.
for (int pageNum = 0; pageNum < number_of_pages;) {
currentPageNumber++;
pageOfCurrentReaderPDF++;
page = PDFCombiner.getImportedPage(pdfReader, ++pageNum);
ColumnText.showTextAligned(stamp.getUnderContent(),
Element.ALIGN_RIGHT, new Phrase(String
.format("%d", currentPageNumber),new Font(FontFamily.TIMES_ROMAN,3)),
50, 50, 0);
stamp.alterContents();
PDFCombiner.addPage(page);
}
}
PDFJoinInJava.close();
You're asking for something that should be trivial, but that isn't. Please take a look at the MergeWithToc example. You'll see that your code to merge PDFs is correct, but in my example, I added one extra feature:
chunk = new Chunk(String.format("Page %d", pageNo));
if (i == 1)
chunk.setLocalDestination("p" + pageNo);
ColumnText.showTextAligned(stamp.getUnderContent(),
Element.ALIGN_RIGHT, new Phrase(chunk), 559, 810, 0);
For every first page, I define a named destination as a local destination. We use p followed by the page number as its name.
We'll use these named destinations in an extra page that will serve as a TOC:
PdfReader reader = new PdfReader(SRC3);
page = copy.getImportedPage(reader, 1);
stamp = copy.createPageStamp(page);
Paragraph p;
PdfAction action;
PdfAnnotation link;
float y = 770;
ColumnText ct = new ColumnText(stamp.getOverContent());
ct.setSimpleColumn(36, 36, 559, y);
for (Map.Entry<Integer, String> entry : toc.entrySet()) {
p = new Paragraph(entry.getValue());
p.add(new Chunk(new DottedLineSeparator()));
p.add(String.valueOf(entry.getKey()));
ct.addElement(p);
ct.go();
action = PdfAction.gotoLocalPage("p" + entry.getKey(), false);
link = new PdfAnnotation(copy, 36, ct.getYLine(), 559, y, action);
stamp.addAnnotation(link);
y = ct.getYLine();
}
ct.go();
stamp.alterContents();
copy.addPage(page);
In my example, I assume that the TOC fits on a single page. You'll have to keep track of the y value and create a new page if its value is lower than the bottom margin.
If you want the TOC to be the first page, you need to reorder the pages in a second go. This is shown in the MergeWithToc2 example:
reader = new PdfReader(baos.toByteArray());
n = reader.getNumberOfPages();
reader.selectPages(String.format("%d, 1-%d", n, n-1));
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(filename));
stamper.close();

Categories

Resources