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)
}
}
Related
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");
}
}
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.
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
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);
}
Trying to add a text to a multi-paged (multiple image) tiff file.
to make the process the text is added correctly, but the image created is not equal to the original zoom (scale) of content changes. I do not know how to make it equal to the original image.
This is the code I use:
File file = new File("AA005E57.tif");
SeekableStream seekableStream = new FileSeekableStream(file);
BufferedImage bsrc = ImageIO.read(file);
ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", seekableStream, null);
int numPages = decoder.getNumPages();
BufferedImage image[]= new BufferedImage[numPages];
for(int i=0;i<decoder.getNumPages();i++){
PlanarImage op1 = new NullOpImage(decoder.decodeAsRenderedImage(i), null, null, OpImage.OP_IO_BOUND);
BufferedImage pg1 = convertRenderedImage(op1);// (new BufferedImage(op1.getWidth(), op1.getHeight(),BufferedImage.TYPE_BYTE_BINARY));
image[i] = pg1;
Graphics2D g2 = image[i].createGraphics();
float pageWidthInch = image[i].getWidth() * 72 / 200;
float pageHeightInch = image[i].getHeight() * 72 / 100;
g2.scale(pageWidthInch, pageHeightInch);
if (i == 0 ){
Font font = new Font("Helvetica", Font.BOLD, 12);
g2.setColor(Color.black);
g2.setFont(font);
g2.drawString("RADICADO 1234567890214365-D", 25,pg1.getHeight()-25);
}
g2.drawImage(image[i], (image[i].getWidth()),image[i].getHeight() ,null);
g2.dispose();
}
save(image,"C:/Prueb-18.tif");
Code for convertRenderedImage:
if (img instanceof BufferedImage) {
return (BufferedImage)img;
}
ColorModel cm = img.getColorModel();
float pageWidthInch = img.getWidth() * 72 / 200;
float pageHeightInch = img.getHeight() * 72 / 100;
WritableRaster raster = cm.createCompatibleWritableRaster( (int)pageWidthInch,(int)pageHeightInch);
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
Hashtable properties = new Hashtable();
String[] keys = img.getPropertyNames();
if (keys!=null) {
for (int i = 0; i < keys.length; i++) {
properties.put(keys[i], img.getProperty(keys[i]));
}
}
BufferedImage result = new BufferedImage(cm, raster, false, properties);
img.copyData(raster);
return result;
Code for Save method:
Iterator writers = ImageIO.getImageWritersByFormatName("TIFF");
if (writers == null || !writers.hasNext()) {
throw new RuntimeException("No writers are available.");
}
FileImageOutputStream fios = new FileImageOutputStream(new File(tif));
ImageWriter writer = (ImageWriter) writers.next();
writer.setOutput(fios);
writer.prepareWriteSequence(null);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("CCITT T.4");
for (int i = 0; i < b.length; i++) {
ImageTypeSpecifier imageType = ImageTypeSpecifier.createFromRenderedImage(b[i]);
IIOMetadata imageMetadata = writer.getDefaultImageMetadata(imageType, param);
imageMetadata = createImageMetadata(imageMetadata);
writer.writeToSequence(new IIOImage(b[i], null, imageMetadata),param);
}
writer.endWriteSequence();
writer.dispose();
writer = null;
fios.close();
}
Code for createImageMetadata:
char[] COMPRESSION = new char[] { (char) BaselineTIFFTagSet.COMPRESSION_CCITT_T_4 };
char[] INCH_RESOLUTION_UNIT = new char[] { 2 };
char[] BITS_PER_SAMPLE = new char[] { 1 };
long[][] X_DPI_RESOLUTION = new long[][] { { 200, 1 } };
long[][] Y_DPI_RESOLUTION = new long[][] { { 200, 1 } };
TIFFDirectory ifd = TIFFDirectory.createFromMetadata(imageMetadata);
BaselineTIFFTagSet base = BaselineTIFFTagSet.getInstance();
TIFFTag tagResUnit = base.getTag(BaselineTIFFTagSet.TAG_RESOLUTION_UNIT);
TIFFTag tagXRes = base.getTag(BaselineTIFFTagSet.TAG_X_RESOLUTION);
TIFFTag tagYRes = base.getTag(BaselineTIFFTagSet.TAG_Y_RESOLUTION);
TIFFTag tagBitSample = base.getTag(BaselineTIFFTagSet.TAG_BITS_PER_SAMPLE);
TIFFTag tagRowStrips = base.getTag(BaselineTIFFTagSet.TAG_ROWS_PER_STRIP);
TIFFTag tagCompression = base.getTag(BaselineTIFFTagSet.TAG_COMPRESSION);
TIFFField fieldResUnit = new TIFFField(tagResUnit, TIFFTag.TIFF_SHORT, 1, INCH_RESOLUTION_UNIT);
TIFFField fieldXRes = new TIFFField(tagXRes, TIFFTag.TIFF_RATIONAL, 1, X_DPI_RESOLUTION);
TIFFField fieldYRes = new TIFFField(tagYRes, TIFFTag.TIFF_RATIONAL, 1, Y_DPI_RESOLUTION);
TIFFField fieldBitSample = new TIFFField(tagBitSample, TIFFTag.TIFF_SHORT, 1, BITS_PER_SAMPLE);
TIFFField fieldCompression = new TIFFField(tagCompression, TIFFTag.TIFF_SHORT, 1, COMPRESSION);
ifd.addTIFFField(fieldResUnit);
ifd.addTIFFField(fieldXRes);
ifd.addTIFFField(fieldYRes);
ifd.addTIFFField(fieldBitSample);
ifd.addTIFFField(fieldCompression);
return ifd.getAsMetadata();
}
The following code is inconsistent:
float pageWidthInch = image[i].getWidth() * 72 / 200;
float pageHeightInch = image[i].getHeight() * 72 / 100;
Is your source DPI 200x100? Be consistent on input; choose 100 or 200. This might be the source of your problem, especially since you save both as 200 for output. Both should likely be the same value, unless your source uses a different DPI for height and width.
Note that this code appears twice in your submitted code above.
If you need to, use AsTiffTagViewer (free application I have found invaluable for examining TIFF files) on your source image to confirm the appropriate values of each page.
Alternately after further review, you do this:
g2.scale(pageWidthInch, pageHeightInch);
Have you considered leaving out this call to g2.scale()?