itextpdf-5.0.6 output image is unexpectedly rotated - java

public static PdfPCell createValueCell(String val, AdditionalInfo addInfo) throws Exception {
PdfPCell valueCell = new PdfPCell();
setBorders(valueCell, 0, 0, 1, 0);
valueCell.setBorderColorBottom(new BaseColor(242, 242, 242));
valueCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
Font cellFont = FontFactory.getFont(FontFactory.HELVETICA, 10);
switch (addInfo.getOptionType()) {
case (OPTION_TYPE_MEDIA):
Image img = null;
try {
img = Image.getInstance(Base64.decode(val));
} catch (Exception e) {
throw new Exception("Problem in decoding image");
}
String mediaName = addInfo.getMediaName();
String imgName = String.format("File: %s", mediaName);
Font captionFont = FontFactory.getFont(FontFactory.HELVETICA, 6);
Paragraph caption = new Paragraph(imgName, captionFont);
valueCell.addElement(img);
valueCell.addElement(caption);
break;
default:
valueCell.setPhrase(new Phrase(val, cellFont));
}
return valueCell;
}
I'm using this code to insert in a cell some data, when the data is an image I use a switch to insert it.
Now I'm having some problems with a standard base64 image, its a Rectangle: 4160.0x3120.0 (rot: 0 degrees) but in the PDF build by my application this image is basically rotated by 90° and I'm pretty sure that I don't apply any kind of rotation to it.
I attach the Table creation:
public static PdfPTable createTableStructure(String groupTag) {
PdfPTable table = new PdfPTable(4);
table.setWidthPercentage(100);
table.getDefaultCell().setBorder(0);
PdfPCell headerCell = new PdfPCell();
headerCell.setBackgroundColor(new BaseColor(216, 216, 216)); //dark gray
headerCell.setBorder(Rectangle.NO_BORDER);
Font headerFont = FontFactory.getFont(FontFactory.HELVETICA, 14);
headerCell.setPhrase(new Phrase(groupTag, headerFont));
headerCell.setColspan(4);
table.addCell(headerCell);
table.setSpacingAfter(20);
table.setHeaderRows(1);
table.completeRow();
return table;
}
When a cell is ready I basically make this call:
table.addCell(valueCell);

Maybe the image is rotated on the original file.
try to check the Orientation. maybe you need to Rotate the image
[question]Get Image Orientation and rotate as per orientation
byte[] bytes = Convert.FromBase64String(val);
Image img;
using (MemoryStream ms = new MemoryStream(bytes))
{
img= Image.FromStream(ms);
}
if (img.PropertyIdList.Contains(274))
{
PropertyItem propOrientation = img.GetPropertyItem(274);
short orientation = BitConverter.ToInt16(propOrientation.Value, 0);
_logger.Info($" orientation {orientation}");
if (orientation == 6)
{
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
bytesro = ImageToByteArray(img);
_logger.Info("after RotateFlipType.Rotate90FlipNone");
}
else if (orientation == 8)
{
img.RotateFlip(RotateFlipType.Rotate270FlipNone);
bytesro = ImageToByteArray(img);
_logger.Info("after RotateFlipType.Rotate270FlipNone");
}
else
{
// Do nothing
bytesro = ImageToByteArray(img);
_logger.Info("after Do nothing");
}
}

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)
}
}

Apache POI will not set superscript inside a TextBox

I need to use Apache POI(4.1.1) to write some text inside a textbox (or rectangle shape), and this text must have superscripts in it. I can get this to work for data inside a cell, but not when using a textbox. Here is a minimal example:
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileOutputStream;
public class SuperScriptTest {
public static void main(String[] args) throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet ws = wb.createSheet("Sheet 1");
XSSFFont fontInfo = wb.createFont();
fontInfo.setFontName("Arial");
fontInfo.setFontHeightInPoints((short) 11);
XSSFFont fontInfoSuperscript = wb.createFont();
fontInfoSuperscript.setFontName("Arial");
fontInfoSuperscript.setFontHeightInPoints((short) 11);
fontInfoSuperscript.setTypeOffset(Font.SS_SUPER);
fontInfoSuperscript.setColor(IndexedColors.RED.getIndex());
Row row = ws.createRow(0);
Cell cell = row.createCell(0);
// Writing to a cell produces desired results:
XSSFRichTextString richString = new XSSFRichTextString("Level3");
richString.applyFont(fontInfo);
richString.applyFont(5, 6, fontInfoSuperscript);
cell.setCellValue(richString);
// Writing to a textbox does not:
XSSFDrawing drawing = ws.createDrawingPatriarch();
XSSFTextBox txtBox = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 0, 5, 2, 7));
XSSFRichTextString richString2 = new XSSFRichTextString("Level3");
richString2.applyFont(fontInfo);
richString2.applyFont(5, 6, fontInfoSuperscript);
txtBox.setText(richString2);
try (FileOutputStream fileOut = new FileOutputStream("Superscript.xlsx")) {
wb.write(fileOut);
}
}
}
The cell will give me the right font and size, and properly superscript the 3 and turn it red.
The textbox will give me the correct font and size, and will color the 3, but it will not superscript the 3.
Thank you for any help.
In Excel cells and text box shapes have different kinds of font settings. For Excel cells spreadsheet settings are used while for text box shapes drawing settings are used.
Because XSSFRichTextString mostly gets used for Excel cell values and shared strings, it internally uses spreadsheet settings. When it comes to XSSFRichTextStrings in context of shapes, the settings need to be converted. This is done in XSSFSimpleShape.setText(XSSFRichTextString str) using the method XSSFSimpleShape.applyAttributes(CTRPrElt pr, CTTextCharacterProperties rPr).
In spreadsheet settings CTRPrElt there is a CTVerticalAlignFontProperty used to set baseline, superscript or subscript. In drawing settings CTTextCharacterProperties there is a baseline attrtibute used which is 0 for baseline, +n% for superscript and -n% for subscript. There n% is the distance from the baseline.
Until now the XSSFSimpleShape.applyAttributes lacks converting CTVerticalAlignFontProperty to CTTextCharacterProperties.setBaseline. To get this, one could patching XSSFSimpleShape.applyAttributes like so:
private static void applyAttributes(CTRPrElt pr, CTTextCharacterProperties rPr) {
...
if (pr.sizeOfVertAlignArray() > 0) {
CTVerticalAlignFontProperty vertAlign = pr.getVertAlignArray(0);
if (vertAlign.getVal() == STVerticalAlignRun.BASELINE) {
rPr.setBaseline(0);
} else if (vertAlign.getVal() == STVerticalAlignRun.SUPERSCRIPT) {
rPr.setBaseline(30000); //30% distance from baseline == default superscript
} else if (vertAlign.getVal() == STVerticalAlignRun.SUBSCRIPT) {
rPr.setBaseline(-25000); //-25% distance from baseline == default subscript
}
}
}
For superscript 30% distance from baseline is choosen because that is the default when someone ticks text effect superscript in text box font settings. For subscript -25% distance from baseline is choosen because that is the default when someone ticks text effect subscript in text box font settings.
Complete example having own setText and applyAttributes to show that it works:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.main.*;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.*;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
import org.apache.poi.hssf.util.HSSFColor;
import java.io.FileOutputStream;
public class SuperScriptTest {
static void setText(XSSFSimpleShape shape, XSSFRichTextString str) {
XSSFWorkbook wb = (XSSFWorkbook) shape.getDrawing().getParent().getParent();
//str.setStylesTableReference(wb.getStylesSource()); // cannot be done here since XSSFRichTextString.setStylesTableReference has protected access
CTTextParagraph p = CTTextParagraph.Factory.newInstance();
if (str.numFormattingRuns() == 0) {
CTRegularTextRun r = p.addNewR();
CTTextCharacterProperties rPr = r.addNewRPr();
rPr.setLang("en-US");
rPr.setSz(1100);
r.setT(str.getString());
} else {
for (int i = 0; i < str.getCTRst().sizeOfRArray(); i++) {
CTRElt lt = str.getCTRst().getRArray(i);
CTRPrElt ltPr = lt.getRPr();
if (ltPr == null) {
ltPr = lt.addNewRPr();
}
CTRegularTextRun r = p.addNewR();
CTTextCharacterProperties rPr = r.addNewRPr();
rPr.setLang("en-US");
applyAttributes(ltPr, rPr);
r.setT(lt.getT());
}
}
//clearText(); //replaced by it's code, 3 lines below
shape.getTextParagraphs().clear();
CTTextBody txBody = shape.getCTShape().getTxBody();
txBody.setPArray(null); // remove any existing paragraphs
CTShape ctShape = shape.getCTShape();
ctShape.getTxBody().setPArray(new CTTextParagraph[] { p });
//shape.getTextParagraphs().add(new XSSFTextParagraph(ctShape.getTxBody().getPArray(0), ctShape)); // cannot be done here since XSSFTextParagraph contructor is not public
}
static void applyAttributes(CTRPrElt pr, CTTextCharacterProperties rPr) {
if (pr.sizeOfBArray() > 0) {
rPr.setB(pr.getBArray(0).getVal());
}
if (pr.sizeOfUArray() > 0) {
STUnderlineValues.Enum u1 = pr.getUArray(0).getVal();
if (u1 == STUnderlineValues.SINGLE) {
rPr.setU(STTextUnderlineType.SNG);
} else if (u1 == STUnderlineValues.DOUBLE) {
rPr.setU(STTextUnderlineType.DBL);
} else if (u1 == STUnderlineValues.NONE) {
rPr.setU(STTextUnderlineType.NONE);
}
}
if (pr.sizeOfIArray() > 0) {
rPr.setI(pr.getIArray(0).getVal());
}
if (pr.sizeOfRFontArray() > 0) {
CTTextFont rFont = rPr.isSetLatin() ? rPr.getLatin() : rPr.addNewLatin();
rFont.setTypeface(pr.getRFontArray(0).getVal());
}
if (pr.sizeOfSzArray() > 0) {
int sz = (int) (pr.getSzArray(0).getVal() * 100);
rPr.setSz(sz);
}
if (pr.sizeOfColorArray() > 0) {
CTSolidColorFillProperties fill = rPr.isSetSolidFill() ? rPr.getSolidFill() : rPr.addNewSolidFill();
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor xlsColor = pr.getColorArray(0);
if (xlsColor.isSetRgb()) {
CTSRgbColor clr = fill.isSetSrgbClr() ? fill.getSrgbClr() : fill.addNewSrgbClr();
clr.setVal(xlsColor.getRgb());
} else if (xlsColor.isSetIndexed()) {
HSSFColor indexed = HSSFColor.getIndexHash().get((int) xlsColor.getIndexed());
if (indexed != null) {
byte[] rgb = new byte[3];
rgb[0] = (byte) indexed.getTriplet()[0];
rgb[1] = (byte) indexed.getTriplet()[1];
rgb[2] = (byte) indexed.getTriplet()[2];
CTSRgbColor clr = fill.isSetSrgbClr() ? fill.getSrgbClr() : fill.addNewSrgbClr();
clr.setVal(rgb);
}
}
}
if (pr.sizeOfVertAlignArray() > 0) {
CTVerticalAlignFontProperty vertAlign = pr.getVertAlignArray(0);
if (vertAlign.getVal() == STVerticalAlignRun.BASELINE) {
rPr.setBaseline(0);
} else if (vertAlign.getVal() == STVerticalAlignRun.SUPERSCRIPT) {
rPr.setBaseline(30000); //30% distance from baseline == default superscript
} else if (vertAlign.getVal() == STVerticalAlignRun.SUBSCRIPT) {
rPr.setBaseline(-25000); //-25% distance from baseline == default subscript
}
}
}
public static void main(String[] args) throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet ws = wb.createSheet("Sheet 1");
XSSFFont fontInfo = wb.createFont();
fontInfo.setFontName("Arial");
fontInfo.setFontHeightInPoints((short) 11);
XSSFFont fontInfoSuperscript = wb.createFont();
fontInfoSuperscript.setFontName("Arial");
fontInfoSuperscript.setFontHeightInPoints((short) 11);
fontInfoSuperscript.setTypeOffset(Font.SS_SUPER);
//fontInfoSuperscript.setTypeOffset(Font.SS_SUB);
fontInfoSuperscript.setColor(IndexedColors.RED.getIndex());
Row row = ws.createRow(0);
Cell cell = row.createCell(0);
// Writing to a cell produces desired results:
XSSFRichTextString richString = new XSSFRichTextString("Level3");
richString.applyFont(fontInfo);
richString.applyFont(5, 6, fontInfoSuperscript);
cell.setCellValue(richString);
// Writing to a textbox does not:
XSSFDrawing drawing = ws.createDrawingPatriarch();
XSSFTextBox txtBox = drawing.createTextbox(new XSSFClientAnchor(0, 0, 0, 0, 0, 5, 2, 7));
XSSFRichTextString richString2 = new XSSFRichTextString("Level3");
richString2.applyFont(fontInfo);
richString2.applyFont(5, 6, fontInfoSuperscript);
//txtBox.setText(richString2);
setText(txtBox, richString2);
try (FileOutputStream fileOut = new FileOutputStream("Superscript.xlsx")) {
wb.write(fileOut);
}
}
}

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.

how to add watermark to pdf using itexpdf

i am using following code to generate pdf file, everything is fine and working but i need to add watermark with the pdf file also alternate color to rows generated in pdf table.
response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".pdf\"");
response.setContentType("application/pdf");
PdfWriter.getInstance(document,response.getOutputStream());
try {
document.open();
addTitlePage(document, reportName,path);
/* Image image = Image.getInstance(path+"images/abi.png");
image.setAbsolutePosition(40f, 770f);
image.scaleAbsolute(70f, 50f);
document.add(image);*/
//float[] colsWidth = {1.5f,3f,4f,4f,2f};
List<Float> colsWidth = new ArrayList<Float>();
int iterator = 1;
while (iterator <= headerMap.size()) {
if(iterator==1){
colsWidth.add(1.5f);
}else{
colsWidth.add(3f);
}
iterator++;
}
float[] floatArray = ArrayUtils.toPrimitive(colsWidth.toArray(new Float[0]), 0.0F);
PdfPTable table = new PdfPTable(floatArray);
table.setWidthPercentage(98);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
PdfPCell c1 = new PdfPCell();
for (Iterator it = headerMap.keySet().iterator(); it.hasNext();) {
String headerName = (String) headerMap.get(it.next());
c1 = new PdfPCell(new Phrase(headerName, headerFont));
c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(c1);
}
table.setHeaderRows(1);
table = custDAO.creadPDFTable(query, table);
document.add(table);
document.addAuthor(userViewModel.getUsername());
document.addCreationDate();
document.addCreator("POC");
document.close();
response.flushBuffer();
private static void addTitlePage(Document document, String reportName,String path) throws DocumentException, MalformedURLException, IOException {
Paragraph preface = new Paragraph();
addEmptyLine(preface, 1);
/**
* Lets write a big header
*/
Paragraph paragraph = new Paragraph(reportName, titleFont);
paragraph.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph);
/**
* Add one empty line
*/
addEmptyLine(preface, 1);
document.add(preface);
Image image = Image.getInstance(path+"/"+"/abilogo.PNG");
image.setAbsolutePosition(40f, 770f);
image.scaleAbsolute(70f, 50f);
document.add(image);
}
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
and this the method i use to create pdftable.(rows)
public PdfPTable creadPDFTable(String query,PdfPTable table){
int numberOfColumns=0,sno=1;
Connection connection = getConnection();
if (connection != null) {
try {
PreparedStatement reportTablePS = connection.prepareStatement(query);
ResultSet reportTable_rst = reportTablePS.executeQuery();
ResultSetMetaData reportTable_rsmd = reportTable_rst.getMetaData();
numberOfColumns = reportTable_rsmd.getColumnCount();
while (reportTable_rst.next()) {
table.addCell(new PdfPCell(new Paragraph(String.valueOf(sno), textFont)));
for (int columnIterator = 1; columnIterator <= numberOfColumns; columnIterator++) {
String column = reportTable_rst.getString(columnIterator);
table.addCell(new PdfPCell(new Paragraph(column, textFont)));
}
sno++;
}
} catch (Exception ex) {
ex.printStackTrace();
}finally {
try {
closeConnection(connection, null, null);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return table;
}
my main concern is to add watermark also adding alternate color to rows.
Please help to resolve this as i am unable to fix this for long time.
Regards
If you want add an watermark as a image u can use the code below. An other way to add a text watermark is to use annotations.
PdfReader pdfReader = null;
Stream outputStream = null;
PdfStamper pdfStamper = null;
try
{
pdfReader = GetPdfReaderObject();
outputStream = new FileStream(filePathDestination, FileMode.Create, FileAccess.Write, FileShare.None);
pdfStamper = new PdfStamper(pdfReader, outputStream);
PdfLayer layer = new PdfLayer("watermark", pdfStamper.Writer);
for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++) {
pdfStamper.FormFlattening = false;
iTextSharp.text.Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(pageIndex);
PdfContentByte pdfData = pdfStamper.GetOverContent(pageIndex);
pdfData.BeginLayer(layer);
PdfGState graphicsState = new PdfGState();
graphicsState.FillOpacity = 0.5F;
pdfData.SetGState(graphicsState);
pdfData.BeginText();
iTextSharp.text.Image watermarkImage = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromFile(watermarkImagePath), ImageFormat.Png);
float width = pageRectangle.Width;
float height = pageRectangle.Height;
watermarkImage.SetAbsolutePosition(width / 2 - watermarkImage.Width / 2, height / 2 - watermarkImage.Height / 2);
pdfData.AddImage(watermarkImage);
pdfData.EndText();
pdfData.EndLayer();
}
}
pdfStamper.Close();
outputStream.Close();
outputStream.Dispose();
pdfReader.Close();
pdfReader.Dispose();
} catch (Exception e) {
....
}
}
And not forget to remove the watermark if you want to add an other watermark.

how to create pdf file in java with alternate colored rows and picture at the top

I am generating pdf file using com.itextpdf.text.* following is my code which creates the pdf file with title and header higlighted and rows, what i wanted to do is, create a pdf file with image on the top and rows with alternate color, how to do this in using com.itextpdf.text.*
response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".pdf\"");
response.setContentType("application/pdf");
PdfWriter.getInstance(document,response.getOutputStream());
try {
document.open();
addTitlePage(document, reportName);
//float[] colsWidth = {1.5f,3f,4f,4f,2f};
List<Float> colsWidth = new ArrayList<Float>();
int iterator = 1;
while (iterator <= headerMap.size()) {
if(iterator==1){
colsWidth.add(1.5f);
}else{
colsWidth.add(3f);
}
iterator++;
}
float[] floatArray = ArrayUtils.toPrimitive(colsWidth.toArray(new Float[0]), 0.0F);
PdfPTable table = new PdfPTable(floatArray);
table.setWidthPercentage(98);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
PdfPCell c1 = new PdfPCell();
for (Iterator it = headerMap.keySet().iterator(); it.hasNext();) {
String headerName = (String) headerMap.get(it.next());
c1 = new PdfPCell(new Phrase(headerName, headerFont));
c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(c1);
}
table.setHeaderRows(1);
table = custDAO.creadPDFTable(query, table);
document.add(table);
document.addAuthor(userViewModel.getUsername());
document.addCreationDate();
document.addCreator("POC");
document.close();
response.flushBuffer();
public PdfPTable creadPDFTable(String query,PdfPTable table){
int numberOfColumns=0,sno=1;
Connection connection = getConnection();
if (connection != null) {
try {
PreparedStatement reportTablePS = connection.prepareStatement(query);
ResultSet reportTable_rst = reportTablePS.executeQuery();
ResultSetMetaData reportTable_rsmd = reportTable_rst.getMetaData();
numberOfColumns = reportTable_rsmd.getColumnCount();
while (reportTable_rst.next()) {
table.addCell(new PdfPCell(new Paragraph(String.valueOf(sno), textFont)));
for (int columnIterator = 1; columnIterator <= numberOfColumns; columnIterator++) {
String column = reportTable_rst.getString(columnIterator);
table.addCell(new PdfPCell(new Paragraph(column, textFont)));
}
sno++;
}
} catch (Exception ex) {
ex.printStackTrace();
}finally {
try {
closeConnection(connection, null, null);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return table;
}
private static void addTitlePage(Document document, String reportName) throws DocumentException {
Paragraph preface = new Paragraph();
addEmptyLine(preface, 1);
/**
* Lets write a big header
*/
Paragraph paragraph = new Paragraph(reportName, titleFont);
paragraph.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph);
/**
* Add one empty line
*/
addEmptyLine(preface, 1);
document.add(preface);
}
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
when i use the following i get the following exception 'getoutputstream() has already called for this response'
i wanted to use this for inserting image.
Image image = Image.getInstance(path+"images/abi.png");
image.setAbsolutePosition(40f, 770f);
image.scaleAbsolute(70f, 50f);
document.add(image);
so how to go about doing this?
UPDATE :
i want to create a pdf file like this i just want to add image on the top and rows with alternate color like this.
http://what-when-how.com/itext-5/decorating-tables-using-table-and-cell-events-itext-5/
(source: what-when-how.com)
(source: what-when-how.com)
You can use XSLFO and Apache FOP. It worked for me. For adding a image I done changes in XSL.
For reference visit
http://www.codeproject.com/Articles/37663/PDF-Generation-using-XSLFO-and-FOP

Categories

Resources