I have a html file which has image in binary form.
I want to convert that to pdf using java.
Can anyone please help me with this?
And the Html file contains Base64 image file
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.text.Chunk;
public class Test{
public static void main(String args[]){
try {
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Test.pdf"));
// step 3
document.open();
document.newPage();
document.add(new Chunk(""));
// step 4
XMLWorkerHelper.getInstance().parseXHtml(writer, document,new FileInputStream("/home/farheen/workspace/html.to.pdf/test.html"));
//step 5
document.close();
System.out.println( "PDF Created!" );
}catch (Exception e) {
e.printStackTrace();
}
}
}
You can use itext
With this example code from here
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
public class ImageExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Image.pdf"));
document.open();
Image image1 = Image.getInstance("watermark.png");
document.add(image1);
String imageUrl = "http://jenkov.com/images/" +
"20081123-20081123-3E1W7902-small-portrait.jpg";
Image image2 = Image.getInstance(new URL(imageUrl));
document.add(image2);
document.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
Related
I'm just beginner in java
I trying to convert PPT file to PDF file using apache poi and Itext library but i'm getting error of NoSuchMethodError
I tried all the version of Apache poi and poi-ooxml but i'm getting same error
please help me to findout Solution for this error
Here is my code :
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.usermodel.SlideShow;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class PPTtoPDF {
public PPTtoPDF() {
}
#SuppressWarnings("resource")
public void convertPPTToPDF(String sourcepath, String destinationPath) throws Exception {
FileInputStream inputStream = new FileInputStream(sourcepath);
double zoom = 2;
AffineTransform at = new AffineTransform();
at.setToScale(zoom, zoom);
Document pdfDocument = new Document();
PdfWriter pdfWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(destinationPath));
PdfPTable table = new PdfPTable(1);
pdfWriter.open();
pdfDocument.open();
Dimension pgsize = null;
Image slideImage = null;
BufferedImage img = null;
SlideShow ppt = new SlideShow(inputStream);
pgsize = ppt.getPageSize();
Slide slide[] = ppt.getSlides();
System.out.println("Length----> "+slide.length);
pdfDocument.setPageSize(new Rectangle((float) pgsize.getWidth(), (float) pgsize.getHeight()));
pdfWriter.open();
pdfDocument.open();
for (int i = 0; i < slide.length; i++) {
img = new BufferedImage((int) Math.ceil(pgsize.width * zoom), (int) Math.ceil(pgsize.height * zoom), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.setTransform(at);
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
slide[i].draw(graphics);
graphics.getPaint();
slideImage = Image.getInstance(img, null);
table.addCell(new PdfPCell(slideImage, true));
System.out.println(table);
}
pdfDocument.add(table);
pdfDocument.close();
pdfWriter.close();
System.out.println("Powerpoint file converted to PDF successfully");
}
public static void main(String[] args) throws Exception
{
PPTtoPDF pp = new PPTtoPDF();
pp.convertPPTToPDF("D:\\tp\\slides.ppt", "D:\\tp\\1.pdf");
}
}
and the error is
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.poi.POIDocument.<init>(Lorg/apache/poi/poifs/filesystem/DirectoryNode;Lorg/apache/poi/poifs/filesystem/POIFSFileSystem;)V
at org.apache.poi.hslf.HSLFSlideShow.<init>(HSLFSlideShow.java:134)
at org.apache.poi.hslf.HSLFSlideShow.<init>(HSLFSlideShow.java:120)
at org.apache.poi.hslf.HSLFSlideShow.<init>(HSLFSlideShow.java:107)
at org.apache.poi.hslf.usermodel.SlideShow.<init>(SlideShow.java:122)
at convertService.PPTtoPDF.convertPPTToPDF(PPTtoPDF.java:44)
at convertService.PPTtoPDF.main(PPTtoPDF.java:75)
See the Apache POI FAQ entry on this very topic. What has almost certainly happened is that you have added a new copy of POI to your classpath, but an older version was already there (from an earlier need, your framework etc), and Java is now getting confused about which one to use.
You could use tool for that:
mvn dependency
tree JDK 8: jdeps
(https://wiki.openjdk.java.net/display/JDK8/Java+Dependency+Analysis+Tool)
jdeps is a new command-line tool added since JDK 8 for developers to
use to understand the static dependencies of their applications and
libraries. jdeps is a static analysis tool on the given class files
I want to create a PDF using image and some text. here image used as mask and text set on different spatial place.
I already generate pdf using image but cannot write text on it.
Here is the image
And output
My code
import com.itextpdf.text.*;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import javax.swing.JFileChooser;
public class Test {
public static void main(String[] args) {
Document document = new Document(PageSize.A4_LANDSCAPE, 0, 0, 0, 0);
String input = "src/icon/orginal_pad.jpg"; // .gif and .jpg are ok too!
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
String filePath = fileChooser.getSelectedFile().getPath();
try {
FileOutputStream fos = new FileOutputStream(filePath);
PdfWriter writer = PdfWriter.getInstance(document, fos);
writer.open();
document.open();
Image im = Image.getInstance(input);
im.scaleToFit(PageSize.A4_LANDSCAPE.getWidth(), PageSize.A4_LANDSCAPE.getHeight());
document.add(im);
//code here
document.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
well,I modified my code to eliminate other factors:
package com.shangzhu.drt;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
/**
* Created by lixiaoming on 2017/6/26.
*/
public class ImageTest2 {
private static void insertImageWithPOI() throws Exception {
XSSFWorkbook wwb = new XSSFWorkbook();
XSSFSheet ws = wwb.createSheet("sheet0");
BufferedImage image = ImageIO.read(new File("D:/poi.png"));
ByteArrayOutputStream baps = new ByteArrayOutputStream();
ImageIO.write(image,"png",baps);
int pictureIdx = wwb.addPicture(baps.toByteArray(), Workbook.PICTURE_TYPE_PNG);
XSSFDrawing drawing = ws.createDrawingPatriarch();
XSSFCreationHelper helper = wwb.getCreationHelper();
XSSFClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(1);
anchor.setRow1(1);
Picture picture = drawing.createPicture(anchor, pictureIdx);
picture.resize();
File excelFile = new File("D:/POI.xlsx");
OutputStream ops = new FileOutputStream(excelFile);
wwb.write(ops);
}
public static void main(String[] args) {
try {
insertImageWithPOI();
} catch (Exception e) {
e.printStackTrace();
}
}
}
below is the picture("D:/poi.png") in the code:
D:/poi.png
I don't think the source code which is dealing image has problems,But I don't know what I missed
I confirm that there is a problem when default column size is used. XSSFPicture.resize needs calculating the column widths in pixels to get the XSSFClientAnchor Col2 and the Dx2. As long as default column size is used, then this calculation seems to be wrong.
A workaround could be defining explicit column sizes before using XSSFPicture.resize. Then the calculation of the column widths in pixels seems to be correct.
In your code:
...
Picture picture = drawing.createPicture(anchor, pictureIdx);
for (int c=0; c<20; c++) ws.setColumnWidth(c, 11*256);
picture.resize();
...
Just like the image, I want to make 1 and 3 align same with 2. The table is default alignment.
What should I do?
Here is a simple way of doing it , add both to the same paragraph
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class ItextMain {
public static final String DEST = "simple_table4.pdf";
public static void main(String[] args) throws IOException, DocumentException {
File file = new File(DEST);
// file.getParentFile().mkdirs();
new ItextMain().createPdf(DEST);
}
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
document.add(new Paragraph("1-Not aligned with table"));
document.add(new Chunk());
Paragraph p = new Paragraph();
p.setIndentationLeft(20);// (20);
PdfPTable table = new PdfPTable(4);
for (int aw = 0; aw < 16; aw++) {
table.addCell("hi");
}
table.setHorizontalAlignment(Element.ALIGN_LEFT);
p.add(table);
//document.add(table);
p.add("3- Aligned with table");
document.add(p);
document.close();
}
}
The iText 5 PdfPTable class has a width percentage attribute which holds the width percentage that the table will occupy in the page. By default this value is 80 and the resulting table is horizontally centered on the page, i.e. in particular it is indented.
To prevent this, simply set the percentage value to 100:
PdfPTable table = ...;
table.setWidthPercentage(100);
Alternatively set the horizontal alignment:
table.setHorizontalAlignment(Element.ALIGN_LEFT);
I am trying to generate pdf file using itext. I need to add an element(Paragraph) above footer in the last page. I don't know how to position the element in that position.
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.ExceptionConverter;
import com.lowagie.text.Image;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfWriter;
public class PdfHeaderDecorator extends PdfPageEventHelper
{
public PdfHeaderDecorator()
{
super();
}
public void onEndPage(PdfWriter writer, Document document)
{
PdfPTable tableF = new PdfPTable(3);
try
{
tableF.setWidths(new int[]
{ 24, 24, 2 });
tableF.setTotalWidth(527);
tableF.setLockedWidth(true);
tableF.getDefaultCell().setFixedHeight(9);
tableF.getDefaultCell().setBorder(Rectangle.BOTTOM);
tableF.addCell(new Phrase("SOME Text"));
tableF.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
tableF.addCell(new Phrase(String.format("page %d ", writer.getPageNumber())));
PdfPCell cell = new PdfPCell(new Phrase("bla bla bla"));
cell.setBorder(Rectangle.BOTTOM);
tableF.addCell(cell);
tableF.writeSelectedRows(0, -1, 34, 30, writer.getDirectContent());
}
catch (DocumentException de)
{
throw new ExceptionConverter(de);
}
}
}
And add your header decorator to page event
pdfWriter.setPageEvent(new PdfHeaderDecorator());