How to display iText Image object in java - java

I am creating a PDF reader in java. For reading PDF files i am using iText library. I have a sample code to read the PDF files but i don't know how to display the iText Image object in a JFrame.Below is the code to read a PDF file.
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
public class ReadAndUsePdf {
private static String INPUTFILE = "c:/temp/FirstPdf.pdf";
private static String OUTPUTFILE = "c:/temp/ReadPdf.pdf";
public static void main(String[] args) throws DocumentException,
IOException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(OUTPUTFILE));
document.open();
PdfReader reader = new PdfReader(INPUTFILE);
int n = reader.getNumberOfPages();
PdfImportedPage page;
// Go through all pages
for (int i = 1; i <= n; i++) {
// Only page number 2 will be included
if (i == 2) {
page = writer.getImportedPage(reader, i);
Image instance = Image.getInstance(page); //how to show this object in a JFrame
document.add(instance);
}
}
document.close();
}
}

I have the exactly same problem, and I solved it by using ICEPdf to render the PDF in Swing, and iText to manipulate it.
Possible duplication: Can I use iText to render PDF in my Swing application?

Related

com.itextpdf.kernel.PdfException: There is no associate PdfWriter for making indirects

I keep getting this error in some pdf file. It works perfectly from some pdf while fails and give error on other pdfs.
Jar used:
forms-7.1.4.jar
io-7.1.4.jar
layout-7.1.4.jar
kernel-7.1.4.jar
package test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.util.*;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.forms.PdfAcroForm;
public class test5 {
public static final String DATASHEET
= "2.pdf";
public static void main(String[] args) throws Exception {
PdfReader reader = new PdfReader(DATASHEET);
PdfDocument pdfDoc = new PdfDocument(reader);
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
Set<String> fields = form.getFormFields().keySet();
for (String key : fields) {
PdfName type = form.getField(key).getFormType();
if(type!= null && 0 == PdfName.Btn.compareTo(type) )
{
String[] states = form.getField(key).getAppearanceStates();
for (int i = 0; i < states.length; i++) {
System.out.println(states[i]);
}
}
}
}
}
PDF FILE
This program finds the radio button values in the pdf
You open the PdfDocument with only a PdfReader, no PdfWriter:
PdfDocument pdfDoc = new PdfDocument(reader);
Thus, you cannot (deeply) change the document. On the other hand you retrieve the AcroForm with the second argument true:
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
This signals to iText that you want it to add a new AcroForm structure to the document if it does not have one yet. This is a deep change.
Thus, your code works for pdfs that already have an AcroForm structure and fail for pdfs that don't.
So either use a writable PdfDocument (with also a PdfWriter) or don't tell iText to create AcroForm structures (with a false parameter). For the latter option you may have to add a null check.

Using PdfCleanUpTool or PdfAutoSweep causes some text to change to bold, line weights increase and double points change to hearts

I have weird problem when I try to use iText 7. Some parts of the PDF are modified (text to change to bold, line weights increase and double points change to hearts). In iText version 5.4.4 this didn't happened, but every version since that I have tried cause this same problem (5 or 7).
Does anyone have a clued why this is happening and is there anything I could to do to bypass this problem? Any help would be appreciated!
If more information is needed, I will try to provide it.
Below is simple code that I used to test iText 7.
Example PDF Files
package javaapplication1;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.pdfcleanup.PdfCleanUpLocation;
import com.itextpdf.pdfcleanup.PdfCleanUpTool;
import com.itextpdf.pdfcleanup.autosweep.ICleanupStrategy;
import com.itextpdf.pdfcleanup.autosweep.PdfAutoSweep;
import com.itextpdf.pdfcleanup.autosweep.RegexBasedCleanupStrategy;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class JavaApplication1 {
public static final String DEST = "D:/TEMP/TEMP/PDF/result/orientation_result.pdf";
public static final String DEST2 = "D:/TEMP/TEMP/PDF/result/orientation_result2.pdf";
public static final String DEST3 = "D:/TEMP/TEMP/PDF/result/orientation_result3.pdf";
public static final String SRC = "D:/TEMP/TEMP/PDF/TEST_PDF.pdf";
public static void main(String[] args) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new JavaApplication1().manipulatePdf(DEST);
new JavaApplication1().manipulatePdf2(DEST2);
try (PdfDocument pdf = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST3))) {
final ICleanupStrategy cleanupStrategy = new RegexBasedCleanupStrategy(Pattern.compile("2019", Pattern.CASE_INSENSITIVE)).setRedactionColor(ColorConstants.PINK);
final PdfAutoSweep autoSweep = new PdfAutoSweep(cleanupStrategy);
autoSweep.cleanUp(pdf);
} catch (Exception e) {
System.out.println(e.toString());
}
}
protected void manipulatePdf(String dest) throws IOException {
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>();
// The arguments of the PdfCleanUpLocation constructor: the number of page to be cleaned up,
// a Rectangle defining the area on the page we want to clean up,
// a color which will be used while filling the cleaned area.
PdfCleanUpLocation location = new PdfCleanUpLocation(1, new Rectangle(97, 405, 383, 40),
ColorConstants.GRAY);
cleanUpLocations.add(location);
PdfCleanUpTool cleaner = new PdfCleanUpTool(pdfDoc, cleanUpLocations);
cleaner.cleanUp();
pdfDoc.close();
}
protected void manipulatePdf2(String dest) throws IOException {
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
// If the second argument is true, then regions to be erased are extracted from the redact annotations
// contained inside the given document. If the second argument is false (that's default behavior),
// then use PdfCleanUpTool.addCleanupLocation(PdfCleanUpLocation)
// method to set regions to be erased from the document.
PdfCleanUpTool cleaner = new PdfCleanUpTool(pdfDoc, true);
cleaner.cleanUp();
pdfDoc.close();
}
}
Sorry for late response. I managed now verify that updating to latest versions corrected this problem. Thanks to #mkl pointing this out.
Problem solved

Convert Extent Report HTML file to PDF

I am trying to convert Extent report HTML file to PDF, however i did not succeed.
Below is the code i tried.
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;
public class Demo
{
public static void main( String[] args ) throws DocumentException, IOException
{
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("pdf.pdf"));
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document,new FileInputStream("html.html"));
document.close();
System.out.println( "PDF Created!" );
}
}
Exception in thread "main" com.itextpdf.tool.xml.exceptions.RuntimeWorkerException: Invalid nested tag head found, expected closing tag link.
at com.itextpdf.tool.xml.XMLWorker.endElement(XMLWorker.java:134)
at com.itextpdf.tool.xml.parser.XMLParser.endElement(XMLParser.java:396)
at com.itextpdf.tool.xml.parser.state.ClosingTagState.process(ClosingTagState.java:70)
at com.itextpdf.tool.xml.parser.XMLParser.parseWithReader(XMLParser.java:236)
at com.itextpdf.tool.xml.parser.XMLParser.parse(XMLParser.java:214)
at com.itextpdf.tool.xml.parser.XMLParser.parse(XMLParser.java:175)
at com.itextpdf.tool.xml.XMLWorkerHelper.parseXHtml(XMLWorkerHelper.java:238)
at com.itextpdf.tool.xml.XMLWorkerHelper.parseXHtml(XMLWorkerHelper.java:210)
at com.itextpdf.tool.xml.XMLWorkerHelper.parseXHtml(XMLWorkerHelper.java:183)
at com.tib.controlStatements.Demo.main(Demo.java:22)
HTML File Link:
https://drive.google.com/open?id=1UrHafoit0rJuhTC0QRqCe9bC5PMpqIWS
Try this example. You did not create the file and trying to fill it.
package sandbox.xmlworker;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import sandbox.WrapToTest;
#WrapToTest
public class D02_ParseHtml {
public static final String HTML = "resources/xml/walden.html";
public static final String DEST = "results/xmlworker/walden1.pdf";
/**
* Html to pdf conversion example.
* #param file
* #throws IOException
* #throws DocumentException
*/
public void createPdf(String file) throws IOException, DocumentException {
// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// step 3
document.open();
// step 4
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new FileInputStream(HTML));
// step 5
document.close();
}
/**
* Main method
*/
public static void main(String[] args) throws IOException, DocumentException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new D02_ParseHtml().createPdf(DEST);
}
}
Finally found a work around for it. So what I have done is Added A css file with some adjustments in to the html and was able to covert to PDF and print with attached screenshots.

PDF Creation for General Health report (sample image attached)

enter image description here
I want to generate the PDF for Health Report on monthly basis for individual person , can any body help to create the PDF .
The sample PDF attached.
you should use iText API for work on PDF creation.
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 = "IPaddress/sitename/images/" +
"imagename.jpg";
Image image2 = Image.getInstance(new URL(imageUrl));
document.add(image2);
document.close();
} catch(Exception e){
e.printStackTrace();
}
}
}

Put image in word document

I am trying to create a word document with apache poi which will contain a jpeg picture. I ve found code to do so from here stackoverflow. However, when I run the code a docx is created, it seems with its size that contains the jpg image but I couldn't open it.
My code is the following:
import org.apache.poi.util.Units;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class SimpleImages {
public static void main(String[] args) throws Exception {
XWPFDocument doc = new XWPFDocument();
XWPFParagraph p = doc.createParagraph();
XWPFRun r = p.createRun();
//for(String imgFile : args) {
String imgFile = "mosaic.jpg";
int format =XWPFDocument.PICTURE_TYPE_JPEG;
r.setText(imgFile);
r.addBreak();
r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels
r.addBreak(BreakType.PAGE);
//}
FileOutputStream out = new FileOutputStream("images.docx");
doc.write(out);
out.close();
}
}
When I tried to open my docx I am receiving:
the file file.docx cannot be opened because there are problems with
the contents
.
I had the same problem but its got resolved. Previously i was using poi 3.10 version and that was culprit for the issue. I just updated it to 3.12 and issue got resolved

Categories

Resources