Hi I have created a PDF file with an image in it, I want to print my pdf after creating. Better if I have the PDF in memory instead of having a file, and then send it to the printer... Any Idea ?
I am using iText. Check my code:
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPrinterGraphics2D;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
private boolean exportToPdfThroughPNG(String fileName, float width, float height) throws DocumentException, IOException {
logger.debug("[boolean exportToPdfQuick() throws IOException, DocumentException]");
BufferedImage pngFile = createPngFile();
Document document = new Document();
document.setPageSize(new Rectangle(width, height));
PdfWriter.getInstance(document, new FileOutputStream(fileName));
document.open();
Image image = Image.getInstance(Toolkit.getDefaultToolkit().createImage(pngFile.getSource()), Color.WHITE);
document.add(image);
// If some day anyone wants to put text in the pdf. #Eduardo
// document.add(new Paragraph("title of the process"));
document.close();
return true;
}
Thanks in advance!
You can always use a ByteArrayOutputStream instead of a FileOutputStream.
After you have the PDF bytes, its a normal "how do you print in Java" question. Many printers (or at least their drivers) will take PDF directly these days, so at that point one could argue that you're done.
PS: Once I tagged your question "Java" it colored your code block using "import" as a keyword and so forth. Something to keep in mind in the future.
Related
This question already has answers here:
FileUtils not showing suggestion to import predefined class for Screenshot functionality in selenium WebDriver
(5 answers)
Closed 4 years ago.
When I try to get screen shots with following code it is showing error.
FileUtils.copyFile(source, new File("*./Screenshots/facebook.png"));
error message
but when i try the following code it is okay.
FileHandler.copy(source,new File("*./Screenshots/facebook.png"));
Why is that?
full code is below
package sample.code;
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.io.FileHandler;
import org.testng.annotations.Test;
public class ScreenShot {
#Test
public void facebookScreenShot() throws IOException {
WebDriver driver= new ChromeDriver();
driver.get("http://www.facebook.com");
driver.manage().window().maximize();
driver.findElement(By.xpath(".//*[#id='u_0_m']")).sendKeys("screenshot");
TakesScreenshot ts=(TakesScreenshot)driver;
File source=ts.getScreenshotAs(OutputType.FILE);
FileHandler.copy(source,new File("*./Screenshots/facebook.png"));
driver.quit();
}
}
By using Robot class ,you can take screenshot.Following is the code to take screenshot.
import java.awt.AWTException;
import java.awt.HeadlessException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class CaptureScreenshot {
public static void main(String[]args) throws IOException, HeadlessException, AWTException
{
// This code will capture screenshot of current screen
BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
// This will store screenshot on Specific location
ImageIO.write(image, "png", new File("C:\\Users\\Screenshot\\CurrentScreenshot.png"));
}
}
is there a way to automatically compress/optimize images in a spring-boot-application?
As in my application the user can put any images in a folder themselves, I cannot make sure, they are compressed the best way. And as they are not uploaded through the application, I can also not create an optimized version.
So what I would like to do is to compress/optimize the images once they are requested and maybe save them in a kind of "image-cache" for a while.
Or is there a tomcat/apache-module, which already does this kind of things out-of-the box?
Thanks for your help
You can use javax.imageio's classes and interface to compress a given image. Below is an example of image compression of JPG image. You can add the below main method code to your service in spring boot application.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
public class ImageCompression {
public static void main(String[] args) throws FileNotFoundException, IOException{
File imageFile = new File("YOUR_IMAGE.jpg");
File compressedImageFile = new File("YOUR_COMPRESSED_IMAGE.jpg");
InputStream inputStream = new FileInputStream(imageFile);
OutputStream outputStream = new FileOutputStream(compressedImageFile);
float imageQuality = 0.3f;
//Create the buffered image
BufferedImage bufferedImage = ImageIO.read(inputStream);
//Get image writers
Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("jpg");
if (!imageWriters.hasNext())
throw new IllegalStateException("Writers Not Found!!");
ImageWriter imageWriter = (ImageWriter) imageWriters.next();
ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream);
imageWriter.setOutput(imageOutputStream);
ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
//Set the compress quality metrics
imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
imageWriteParam.setCompressionQuality(imageQuality);
//Created image
imageWriter.write(null, new IIOImage(bufferedImage, null, null), imageWriteParam);
// close all streams
inputStream.close();
outputStream.close();
imageOutputStream.close();
imageWriter.dispose();
}
}
Good evening
I want to fill in the jpg photo file windows properties
Apparently these are the exiftags
[Exif IFD0] Windows XP Title
[Exif IFD0] Windows XP Author
[Exif IFD0] Windows XP Subject
I looked at the side of icafe.jar but have not found these tags.
Can I make it with icafe or other jar library ?
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import com.icafe4j.image.meta.Metadata;
import com.icafe4j.image.meta.exif.Exif;
import com.icafe4j.image.meta.jpeg.JpegExif;
import com.icafe4j.image.meta.exif.ExifTag;
import com.icafe4j.image.tiff.TiffTag;
import com.icafe4j.image.tiff.FieldType;
fin = new FileInputStream(Fm_filePathIn);
fout = new FileOutputStream(Fm_filePathOut);
List<Metadata> metaList = new ArrayList<Metadata>();
metaList.add(populateExif(JpegExif.class));
Exif populateExif(Class<?> exifClass) throws IOException {
Exif exif = new JpegExif();
exif.addImageField(ExifTag.WINDOWS_XP_AUTHOR, FieldType.WINDOWSXP, "Toto");
exif.addImageField(ExifTag.WINDOWS_XP_KEYWORDS, FieldType.WINDOWSXP, "Copyright;Authorbisou");
// Insert ThumbNailIFD
// Since we don't provide thumbnail image, it will be created later from the input stream
exif.setThumbnailRequired(true);
return exif;
}
fin.close();
fout.close();
Those tags do exist in ICAFE but they are not Exiftag. They are TiffTag. Replace the ExifTag with TiffTag, it will work. Look at the TestMetada.java, it clearly shows that.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.icafe4j.image.meta.Metadata;
import com.icafe4j.image.meta.exif.Exif;
import com.icafe4j.image.meta.jpeg.JpegExif;
import com.icafe4j.image.meta.exif.ExifTag;
import com.icafe4j.image.tiff.TiffTag;
import com.icafe4j.image.tiff.FieldType;
public class TestWindowsXP {
public static void main(String[] args) throws IOException {
FileInputStream fin = new FileInputStream(Fm_filePathIn);
FileOutputStream fout = new FileOutputStream(Fm_filePathOut);
List<Metadata> metaList = new ArrayList<Metadata>();
Exif exif = new JpegExif();
exif.addImageField(TiffTag.WINDOWS_XP_AUTHOR, FieldType.WINDOWSXP, "Toto");
exif.addImageField(TiffTag.WINDOWS_XP_KEYWORDS, FieldType.WINDOWSXP, "Copyright;Authorbisou");
// Insert ThumbNailIFD
// Since we don't provide thumbnail image, it will be created later from the input stream
exif.setThumbnailRequired(true);
metaList.add(exif);
Metadata.insertMetadata(metaList, fin, fout);
fin.close();
fout.close();
}
}
And the following is a screenshot when I right-click the resulting image->show properties. You can see the information you wanted to insert is showing.
I'm a newbie here. I have a simple problem in ONE java source file: the row System.out.pritln(...) has been treated as an erroneous expression. Here's the code snippet:
package vk.gui;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Properties;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BarcodeEAN;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPCellEvent;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class MatrixSheet1 {
Properties p;
File file;
Document document;
PdfWriter writer;
Image logo = null;
Image EANimg = null;
float mnoz = new Double(72/25.6).floatValue();
int IMG_WIDTH= new Double(35*mnoz).intValue();
int IMG_HEIGHT=new Double(35*mnoz).intValue();
String err=p.getProperty("cell.height");
System.out.println("Arrgh!"); ///-------------->ERROR!
float cell_Height = Float.parseFloat(p.getProperty("cell.height"))*mnoz;
float cell_Width = Float.parseFloat(p.getProperty("cell.width"))*mnoz;
The reported error is
Multiple markers at this line
Syntax error on token ""Arrgh!"", delete this token
Syntax error on token(s), misplaced construct(s)
The sout and sysout shortcuts do not work neither. In other existing source files of same package everything is OK, the shortcuts work and the expression does not trigger an error.
I tried to create another source file and copy/paste the content, but I got the same error. What and where went wrong?
I need the printing just for debugging, but this is a bit annoying symptom.
Thanks in advance.
This happens because you can use System.out.println() only inside methodes. If you would do something like this, it would work:
public class MatrixSheet1 {
Properties p;
File file;
Document document;
PdfWriter writer;
Image logo = null;
Image EANimg = null;
float mnoz = new Double(72/25.6).floatValue();
int IMG_WIDTH= new Double(35*mnoz).intValue();
int IMG_HEIGHT=new Double(35*mnoz).intValue();
String err=p.getProperty("cell.height");
systemMessage("Argh!");
float cell_Height = Float.parseFloat(p.getProperty("cell.height"))*mnoz;
float cell_Width = Float.parseFloat(p.getProperty("cell.width"))*mnoz;
private void systemMessage(String message){
System.out.println(message);
}
}
Is there any way to convert generated .ppt file using apache poi to .pdf file?
OR
Any way to convert PPT file to PDF file using JAVA?
Gagravarr, thanks you for your comment with following approach: PPT -> images -> PDF. It gave me clues for further solutions.
Recently, I've faced the same task: convert PPT reports into PDF reports using Java facilities. PPT reports are generated via Apache POI lib, and I intended to reuse ready created PPT structure.
I developed two solutions, each has its own advantages/disadvantages. And both of them using iText library with version 2.1.7.(which is free to use, and which is great)). Both of them do support Japanese symbols after additional enhancement.
1. Apache POI Slide -> image -> PDF
Demonstration code example:
package com.test.pdf;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.usermodel.SlideShow;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfWriter;
public class PPTtoImageToPDFexample {
public static void main(String[] args) throws IOException, DocumentException {
//load any ppt file
FileInputStream inputStream = new FileInputStream("d:/temp/initialPPT.ppt");
SlideShow ppt = new SlideShow(inputStream);
inputStream.close();
Dimension pgsize = ppt.getPageSize();
//take first slide and save it as an image
Slide slide = ppt.getSlides()[0];
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height,
BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width,
pgsize.height));
slide.draw(graphics);
FileOutputStream out = new FileOutputStream("d:/temp/slideImage.png");
javax.imageio.ImageIO.write(img, "png", out);
out.close();
//get saved slide-image and save it into pdf
Image slideImage = Image.getInstance("d:/temp/slideImage.png");
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("d:/temp/PPTtoImageTest.pdf"));
document.setPageSize(new Rectangle(slideImage.getWidth(), slideImage.getHeight()));
document.open();
slideImage.setAbsolutePosition(0, 0);
document.add(slideImage);
document.close();
}
}
2. This approach works on-fly: take Apache POI Slide -> get awt.Graphics2 instance from it -> pass this interface to the iText
draw engine.
Demonstration code example:
package com.test.pdf;
import java.awt.Dimension;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.usermodel.SlideShow;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfGraphics2D;
import com.lowagie.text.pdf.PdfWriter;
public class PPTtoPDFdirectly {
public static void main(String[] args) throws IOException, DocumentException {
//load any ppt file
FileInputStream inputStream = new FileInputStream("d:/temp/initialPPT.ppt");
SlideShow ppt = new SlideShow(inputStream);
inputStream.close();
Dimension pgsize = ppt.getPageSize();
//take first slide and draw it directly into PDF via awt.Graphics2D interface.
Slide slide = ppt.getSlides()[0];
Document document = new Document();
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("d:/temp/PPTtoPDF.pdf"));
document.setPageSize(new Rectangle((float)pgsize.getWidth(), (float) pgsize.getHeight()));
document.open();
PdfGraphics2D graphics = (PdfGraphics2D) pdfWriter.getDirectContent().createGraphics((float)pgsize.getWidth(), (float)pgsize.getHeight());
slide.draw(graphics);
graphics.dispose();
document.close();
}
}
One option is to use POI to convert each slide into an image, then use something like Apache PDFBox to place each image onto it's own PDF page. This should work well for simpler PPT files, but the code to render slides is still a WIP. So, if you have a very complex slide, you may find some bits missing/incorrect, do send in patches if you fix any of these gaps!
Otherwise, your other option is to use the Java bindings for OpenOffice, and have that do the conversion for you