I am using PDF box to create PDF, I am trying to print image into pdf , it works all the format except PNG. Mycode as follows :
String image = "c:/image.png";
PDXObjectImage ximage = null;
if( image.toLowerCase().endsWith( ".jpg" ) )
{
ximage = new PDJpeg(doc, new FileInputStream( image ) );
}
else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff"))
{
ximage = new PDCcitt(doc, new RandomAccessFile(new File(image),"r"));
}
else
{
BufferedImage awtImage = ImageIO.read( new File( image ) );
ximage = new PDPixelMap(doc, awtImage);
throw new IOException( "Image type not supported:" + image );
}
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
contentStream.drawImage( ximage, 20, 20 );
When ever I give png image it is going to the :
else
{
BufferedImage awtImage = ImageIO.read( new File( image ) );
ximage = new PDPixelMap(doc, awtImage);
//throw new IOException( "Image type not supported:" + image );
}
and showing image stream IO exception cant read image file. What changes am I need to make to accept png image also in this? Please help...
String image = "c:/"+rst.getString(8);
PDXObjectImage ximage = null;
if( image.toLowerCase().endsWith( ".jpg" ) )
{
ximage = new PDJpeg(doc, new FileInputStream( image ) );
}
else if (image.toLowerCase().endsWith(".tif") || image.toLowerCase().endsWith(".tiff"))
{
ximage = new PDCcitt(doc, new RandomAccessFile(new File(image),"r"));
}
else
{
BufferedImage awtImage = ImageIO.read( new File( image ) );
ximage = new PDPixelMap(doc, awtImage);
}
contentStream.drawXObject(ximage, 20, pageYaxis-120, 80, 80);
pageYaxis = pageYaxis-56;
Related
I need to decode a DataMatrix in a PDF, in my case the DataMatrix it's not a image.
My first idea was transform the Page to a Image and crop the area with the DataMatrix and after decode, but it seems the (image)result it's corrupted and I can't decode properly. Any idea How I can keep the quality of the PDF??
String sourceDir = "data/test2.pdf";
File pdf = new File(sourceDir);
PDDocument document = PDDocument.load(sourceDir);
List<PDPage> list = document.getDocumentCatalog().getAllPages();
String key;
for (PDPage page : list) {
BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 300);
BufferedImage dest = image.getSubimage(0, 2600, 800, 800);
File outputFile = new File( "data/test2.jpg");
ImageIO.write(dest, "png", outputFile);
LuminanceSource lumSource = new BufferedImageLuminanceSource (dest);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(lumSource));
Hashtable<DecodeHintType, Object> hint = new Hashtable<DecodeHintType, Object>();
hint.put(DecodeHintType.TRY_HARDER, BarcodeFormat.DATA_MATRIX);
DataMatrixReader DMreader = new DataMatrixReader();
try {
Result result = DMreader.decode(bitmap, hint);
System.out.println(result);
}catch(Exception e){
System.out.println("NO Data Matrix");
}
}
}
Version 2.0
PDDocument document = PDDocument.load(new File(sourceDir));
PDFRenderer pdfRenderer = new PDFRenderer(document);
for (int page = 0; page < document.getNumberOfPages(); ++page)
{
BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(page, 600, ImageType.RGB);
BufferedImage datamatrixImg = bufferedImage.getSubimage(150, 6000, 600, 900);
File outputfile = new File("out/image_"+page+".jpg");
ImageIO.write(datamatrixImg, "jpg", outputfile);
LuminanceSource lumSource = new BufferedImageLuminanceSource(datamatrixImg);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(lumSource));
Hashtable<DecodeHintType, Object> hint = new Hashtable<DecodeHintType, Object>();
hint.put(DecodeHintType.TRY_HARDER, BarcodeFormat.DATA_MATRIX);
DataMatrixReader DMreader = new DataMatrixReader();
try {
Result result = DMreader.decode(bitmap, hint);
System.out.println("Decode: "+ result );
} catch (Exception e) {
System.out.println("No DataMatrix");
}
}
document.close();
I am using pdfbox for converting a pdf to image but I am getting only half image of the original . Can somebody please help
String sourceDir = "D:/pdffiles/Sample_93.pdf"; // Pdf files are read from this folder
String destinationDir = "D:/images/png/"; // converted images from pdf document are saved here
File sourceFile = new File(sourceDir);
File destinationFile = new File(destinationDir);
if (!destinationFile.exists()) {
destinationFile.mkdir();
System.out.println("Folder Created -> "+ destinationFile.getAbsolutePath());
}
if (sourceFile.exists()) {
PDDocument document = PDDocument.loadNonSeq(new File(sourceDir), null);
List<PDPage> pdPages = document.getDocumentCatalog().getAllPages();
int page = 0;
for (PDPage pdPage : pdPages){
++page;
BufferedImage bim = pdPage.convertToImage(BufferedImage.TYPE_INT_RGB, 300);
ImageIOUtil.writeImage(bim, "Report" + "-" + page + ".png", 300);
}
document.close();
}
Below was the half image
incomplete image
Edit 1 :
1st page with content came out correctly the 2nd page with the images(its scanned as pdf images) came out only half .
Edit 2
Tried with the below code where the image got turned black areas to white and white areas to black
Total Black Image
public class ImageMain {
public static void setup() throws IOException {
// load a pdf from a byte buffer
File file = new File("D:/odimages/selection.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
int numPgs = pdffile.getNumPages();
for (int i = 0; i < numPgs; i++) {
// draw the first page to an image
PDFPage page = pdffile.getPage(i);
// get the width and height for the doc at the default zoom
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight());
// generate the image
Image img = page.getImage(rect.width, rect.height, // width & height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
// save it as a file
BufferedImage bImg = toBufferedImage(img);
File yourImageFile = new File("D:/odimages/png/page_" + i + ".png");
ImageIO.write(bImg, "png", yourImageFile);
}
}
// This method returns a buffered image with the contents of an image
public static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
}
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();
// Determine if the image has transparent pixels; for this method's
// implementation, see e661 Determining If an Image Has Transparent
// Pixels
boolean hasAlpha = hasAlpha(image);
// Create a buffered image with a format that's compatible with the
// screen
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
// Determine the type of transparency of the new buffered image
int transparency = Transparency.OPAQUE;
if (hasAlpha) {
transparency = Transparency.BITMASK;
}
// Create the buffered image
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {
// The system does not have a screen
}
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
if (hasAlpha) {
type = BufferedImage.TYPE_INT_ARGB;
}
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}
// Copy image to buffered image
Graphics g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
public static boolean hasAlpha(Image image) {
// If buffered image, the color model is readily available
if (image instanceof BufferedImage) {
BufferedImage bimage = (BufferedImage) image;
return bimage.getColorModel().hasAlpha();
}
// Use a pixel grabber to retrieve the image's color model;
// grabbing a single pixel is usually sufficient
PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
try {
pg.grabPixels();
} catch (InterruptedException e) {
}
// Get the image's color model
ColorModel cm = pg.getColorModel();
return cm.hasAlpha();
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
ImageMain.setup();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
}
Stuck with PDFBox-Android, pdfbox-android:1.8.9.0
I load first page of a pdf file, write text in and import this page to a new page of a final document.
Problem is when create new pages, it use last page which contain previous text...
So, first page is ok, but nexts have texts superposed..
private File writeReport() {
File fileSource = new File(getActivity().getApplicationContext().getExternalCacheDir(), "fileSource.pdf");
// get file model in assets
InputStream inputAsset = null;
try {
inputAsset = getActivity().getApplicationContext().getResources().getAssets().open("file_model.pdf");
} catch (IOException e) {
e.printStackTrace();
}
// copy file model in fileSource
try {
OutputStream outputStream = new FileOutputStream(file);
byte buffer[] = new byte[1024];
int length = 0;
while ((length = inputAsset.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputAsset.close();
} catch (IOException e) {
System.out.print("Copy assets : IOException" + e.getMessage());
}
File fileTarget = new File(getActivity().getApplicationContext().getCacheDir(), "fileTarget.pdf");
try {
PDFBoxResourceLoader.init(getActivity().getApplicationContext()); // init lib
PDDocument documentSource = PDDocument.load(fileSource);
PDDocument documentTarget = new PDDocument();
// iteration == a new page
for(int i=0 ; i < 3 ; i++)
{
PDPage page = documentSource.getDocumentCatalog().getPages().get(0);
PDPageContentStream contentStream = new PDPageContentStream(documentSource, page, true, true);
PDFont font1 = PDType1Font.HELVETICA;
float startY = page.getMediaBox().getUpperRightY();
float factor = 2.83f;
page.getStream();
// add text
contentStream.beginText();
contentStream.setFont(font1, 10);
contentStream.newLineAtOffset(factor * 60, startY - (factor * 53));
contentStream.showText("test text" + i);
contentStream.endText();
contentStream.close();
// import source page to output file-> Problem here ! new page contain old overlay text...
documentTarget.importPage(page);
}
documentTarget.save(fileTarget);
documentTarget.close();
documentSource.close();
} catch (IOException e) {
e.printStackTrace();
}
return fileTarget;
}
Is there a way to have fresh page at every iteration ?
Thanks !
The problem is that you reused the same PDPage object, which resulted in the effect that it contained the text of the previous iteration. Solution: use the result of
documentTarget.importPage(page)
and work with that one. Because that is a new PDPage object with everything cloned. So your new code will be like this:
// iteration == a new page
for(int i=0 ; i < 3 ; i++)
{
PDPage page = documentSource.getDocumentCatalog().getPages().get(0);
page = documentTarget.importPage(page); // this is now a new PDPage object
PDPageContentStream contentStream = new PDPageContentStream(documentSource, page, true, true);
PDFont font1 = PDType1Font.HELVETICA;
float startY = page.getMediaBox().getUpperRightY();
float factor = 2.83f;
page.getStream();
// add text
contentStream.beginText();
contentStream.setFont(font1, 10);
contentStream.newLineAtOffset(factor * 60, startY - (factor * 53));
contentStream.showText("test text" + i);
contentStream.endText();
contentStream.close();
}
I am using the following code to merge two pdfs:
File firstPdfFile = new File("firstPdf.pdf");
File secondPdfFile = new File("secondPdf.pdf");
PDFMergerUtility merger = new PDFMergerUtility();
merger.addSource(firstPdfFile);
merger.addSource(secondPdfFile);
String pdfPath = "PdfFile.pdf";
OutputStream bout2 = new BufferedOutputStream(new FileOutputStream(pdfPath));
merger.setDestinationStream(bout2);
merger.mergeDocuments();
File pdfFile = new File(pdfPath);
I am getting the merged pdf correctly but I want to add page number in this pdf file.
Try this code.
File firstPdfFile = new File("firstPdf.pdf");
File secondPdfFile = new File("firstPdf.pdf");
PDFMergerUtility merger = new PDFMergerUtility();
merger.addSource(firstPdfFile);
merger.addSource(secondPdfFile);
String pdfPath = "PdfFile.pdf";
OutputStream bout2 = new BufferedOutputStream(new FileOutputStream(pdfPath));
merger.setDestinationStream(bout2);
merger.mergeDocuments();
PDDocument doc = null;
try {
URL file = new URL("file:///PdfFile.pdf");
doc = PDDocument.load(file);
List<?> allPages = doc.getDocumentCatalog().getAllPages();
PDFont font = PDType1Font.HELVETICA_BOLD;
float fontSize = 36.0f;
for (int i = 0; i < allPages.size(); i++) {
PDPage page = (PDPage) allPages.get(i);
PDPageContentStream footercontentStream = new PDPageContentStream(doc, page, true, true);
footercontentStream.beginText();
footercontentStream.setFont(font, fontSize);
footercontentStream.moveTextPositionByAmount((PDPage.PAGE_SIZE_A4.getUpperRightX() / 2), (PDPage.PAGE_SIZE_A4.getLowerLeftY()));
footercontentStream.drawString(String.valueOf(i + 1));
footercontentStream.endText();
footercontentStream.close();
}
doc.save("PdfFile.pdf");
} finally {
if (doc != null) {
doc.close();
}
}
Try below code for PDFBox 2.0
public class PageNumberExample {
final boolean isCompress = false;
final boolean isContextReset = true;
public static void main(String[] args) throws IOException {
new PageNumberExample().addPageNumber("merged PDF path");
}
public void addPageNumber(String pdfPath) throws IOException {
File mergePpdfFile = new File(pdfPath);
PDDocument document = PDDocument.load(mergePpdfFile);
int totalPage = document.getNumberOfPages();
for(int i=0; i<totalPage; i++) {
PDPage page = document.getPage(i);
PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, isCompress, isContextReset);
stream.setNonStrokingColor(Color.BLACK);
stream.beginText();
stream.setFont(PDType1Font.COURIER, 10);
stream.newLineAtOffset(100, 100); //Set position where you want to print page number.
stream.showText("Page " + (i+1) + " of " + totalPage);
stream.endText();
stream.close();
}
document.save(pdfPath);
document.close();
}
}
I am trying to add an image to a report template. I am adding the String values with this code:
form.setField("name", name);
But I can not add an image to the form using a similar code:
form.setField("photo", photo);
I searched the web but couldn't find a solution. The whole code is:
public static ByteArrayOutputStream personelSicilFormOlustur(String sablonDir, String name, byte[] photo) {
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
BaseFont fontTimes = BaseFont.createFont(sablonDir + "\\" + fontName, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
BaseFont fontTimesBold = BaseFont.createFont(sablonDir + "\\" + fontNameBold, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
BaseFont fontTimesItalic = BaseFont.createFont(sablonDir + "\\" + fontNameItalic, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
PdfReader reader = new PdfReader(sablonDir + "\\" + tmSablonForSicilKaydiName);
PdfStamper stamper = new PdfStamper(reader, baos);
AcroFields form = stamper.getAcroFields();
form.setField("name", name);
form.setField("photo", photo);
stamper.setFormFlattening(true);
stamper.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
return baos;
}
}
I solved the problem with this code:
InputStream photoImage = new ByteArrayInputStream(photo);
BufferedImage bImageFromConvert = ImageIO.read(photoImage);
int type = bImageFromConvert.getType() == 0? BufferedImage.TYPE_INT_ARGB : bImageFromConvert.getType();
BufferedImage dimensionedImage = resizeImage(bImageFromConvert, type);
ImageIO.write(dimensionedImage, "jpg", new File("c:/new-darksouls.jpg"));
Image image1 = Image.getInstance("c:/new-darksouls.jpg");
image1.setAbsolutePosition(450f, 650f);
canvas.addImage(image1);