Itext7 PDF Form Not Editable After Writing Data - itext7

Following code i am using to write data in pdf form. The output Pdf is not editable.
I need editable pdf after updating data.
public static void main(String[] args) throws IOException {
PdfReader reader = new PdfReader("Input.pdf");
PdfWriter writer = new PdfWriter("Output.pdf");
PdfDocument pdfDocument = new PdfDocument(reader, writer);
//PdfDocument pdfDocument = new PdfDocument(reader, writer,new
StampingProperties().useAppendMode());
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDocument, false);
form.getField("topmostSubform[0].Page1[0].Id[0]").setValue("12345678");
form.getField("topmostSubform[0].Page1[0].Name[0]").setValue("Name");
form.getField("topmostSubform[0].Page1[0].Sno[0]").setValue("11111111111");
form.getField("topmostSubform[0].Page1[0].Status[0]").setValue("Yes");
form.flush();
pdfDocument.close();
}
If i use StampingProperties().useAppendMode() nothing is writing in out put pdf but is editable.

Related

read json file from resources

I'm trying to read json file that located in documents folder into resources file in quarkus.
here is my code:
try(InputStream inputStream = classLoader.getResourceAsStream("documents/helloWorldDocument.json")) {
// Retrieve the JSON document and put into a string/object map
ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<String, Object>> documentMapType =
new TypeReference<HashMap<String, Object>>() {};
//
Map<String, Object> document = mapper.readValue(
new File(inputStream.toString()),
documentMapType);
// Use builder methods in the SDK to create the directive.
RenderDocumentDirective renderDocumentDirective = RenderDocumentDirective.builder()
.withToken("helloWorldToken")
.withDocument(document)
.build();
// Add the directive to a responseBuilder.
responseBuilder.addDirective(renderDocumentDirective);
// Tailor the speech for a device with a screen.
speechText.append(" You should now also see my greeting on the screen.");
} catch (IOException e) {
throw new AskSdkException("Unable to read or deserialize the hello world document", e);
}
but getting exception. really appreciate if anyone could help.
(I'm implementing APL for an alexa skill)
After searching a lot, I solve this:
try {
File file = new File(
Objects.requireNonNull(this.getClass().getClassLoader().getResource("helloWorldDocument.json")).getFile()
);
ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<String, Object>> documentMapType =
new TypeReference<HashMap<String, Object>>() {
};
Map<String, Object> document = mapper.readValue(
new File(file.toString()),
documentMapType);
RenderDocumentDirective renderDocumentDirective = RenderDocumentDirective.builder()
.withToken("helloWorldToken")
.withDocument(document)
.build();
responseBuilder.addDirective(renderDocumentDirective);
speechText.append(" You should now also see my greeting on the screen.");
} catch (IOException e) {
throw new AskSdkException("Unable to read or deserialize the hello world document", e);
}

javax.imageio.ImageIO.read(new ByteArrayInputStream(data)) throws instantiation exception while reading byte array image data

public static void createImage2() {
try {
BufferedImage bImage = ImageIO.read(new File("input.jpg"));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bImage, "jpg", bos );
byte [] data = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(data);
BufferedImage bImage2 = ImageIO.read(bis);
ImageIO.write(bImage2, "jpg", new File("output.jpg") );
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("image created");
}
The method ImageIO.read(bis) throws this exception:
Exception in thread "main" java.util.ServiceConfigurationError: javax.imageio.spi.ImageReaderSpi: Provider com.aware.j2k.imageio.J2KImageReaderSpi could not be instantiated
If you application throw exception with message of SPI - java.util.ServiceLoader don't find library, for add library you must just choose and add dependency f.e. group: com.twelvemonkeys.imageio or another implementation
For reading image to BufferedImage i recommend use
ImageIO.read(new MemoryCacheImageInputStream(new ByteArrayInputStream(file.getBytes())))
if you need create new image i recommend use
ImageTypeSpecifier.createFromRenderedImage(source).createBufferedImage(width, height)
ATTENTION
a lot of function for working with image use disk storage for cache or tmp by default

Generated PDF not send in the browser

I build a PDF document with iText library, and i want to get this document by clicking a link in the webapp.
But, it happens... nothing. No error message, no exception, really nothing.
I really don't master IO Streaming, so I think I made a mistake on this point, but after few hours of research, I don't know and I need a bit of help.
I have two methods. The first is the one to create pdf doc.
public void exporterPDF(SomeObjectIWillUse o) {
Document documentPDF = new Document(PageSize.A4);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(documentPDF, baos);
documentPDF.open();
documentPDF.addTitle("Test ! ");
Paragraph par = new Paragraph("Liste des participants");
documentPDF.add(par)
documentPDF.close();
telechargerPdfViaVue(FacesContext.getCurrentInstance(), baos, "filename.pdf");
} catch (Exception e) {
// TODO Auto-generated catch block
JsfUtils.addMessageByCode(FacesMessage.SEVERITY_FATAL, "drc.export.generation.pdf.erreur");
}
}
And the second is use to send the document.
public static final void telechargerPdfViaVue(FacesContext context, ByteArrayOutputStream baos, String fileName) throws IOException, DocumentException {
ExternalContext externalContext = context.getExternalContext();
externalContext.setResponseContentType("application/pdf");
externalContext.setResponseHeader("Expires", "0");
externalContext.setResponseHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
externalContext.setResponseHeader("Pragma", "public");
externalContext.setResponseHeader("Content-disposition", "attachment;filename=" + fileName);
externalContext.setResponseContentLength(baos.size());
OutputStream out = externalContext.getResponseOutputStream();
baos.writeTo(out);
externalContext.responseFlushBuffer();
context.responseComplete();
}
and it's called on my web page by a simple commandeLink
<p:commandLink id="exportPdf" action="#{myBean.exporterPDF(o)}">
Literally, in debug mode, all is done, but nothing happen...
Thank you for your help!
More informations, I use :
- JSF 2.2.7
- Spring 4.0.6

iText 7 (7.0.2)Error: The method add(AreaBreak) in the type Document is not applicable for the arguments (Paragraph)

I am trying to learn iText7(7.0.2), and building a basic pdf, but encountering an error at document.add(new Paragraph("Hello World!")), saying
The method add(AreaBreak) in the type Document is not applicable for the arguments (Paragraph)"
Any help will be thankful.
public static void main(String args[]) throws IOException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new PdfTest().createPdf(DEST);
}
public void createPdf(String dest) throws IOException {
//Initialize PDF writer
PdfWriter writer = new PdfWriter(dest);
//Initialize PDF document
PdfDocument pdf = new PdfDocument(writer);
// Initialize document
Document document = new Document(pdf);
//Add paragraph to the document
document.add(new Paragraph("Hello World!"));
//Close document
document.close();
}
Just run your example. It's work perfectly fine. My best guess is you have old caches from itextpdf5. Make sure your .pom-file contains only itext7 dependencies. And, as mkl mentioned in his comment, correct way to import Paragraph is
import com.itextpdf.layout.element.Paragraph

Showing the uploaded image in Vaadin with EasyUploads

I'm trying to use EasyUploads-addon for Vaadin, but can't get the image shown.
When I click addon's "Choose File"-button, it will ask me to open an file. I choose some .png -file from my images and addon shows the information of the picture beneath it.
Then I press my "Upload"-button, which is currently needed just to show the uploaded image at first.
private void showUploadedImage() {
Object value = upload.getValue();
byte[] data = (byte[]) value;
StreamResource resource = new StreamResource(
new StreamResource.StreamSource() {
private static final long serialVersionUID = 1L;
#Override
public InputStream getStream() {
return new ByteArrayInputStream(data);
}
}, "filename.png");
image.setVisible(true);
image.setCaption("Uploaded image");
image.setSource(resource);
}
upload = EasyUpload's component which is used to choose file
image = Embedded component that I have drawn with the designer to my layout.
But when I look the page with browser the image is not shown. The image is just shown as there is no image at all, just caption will be shown.
HTML-code of the image from the page's source:
<img src="null">
This might be really trivial case, but all the examples that I found was over 3-4 years old and didn't look helpful.
Can someone tell me, how it should be done?
You need to call a setter on UploadField class:
uploadField.setFieldType(FieldType.BYTE_ARRAY);
Working SSCCE:
#Override
protected void init(VaadinRequest request) {
setContent(layout);
final UploadField uploadField = new UploadField();
uploadField.setAcceptFilter(".png");
uploadField.setFieldType(FieldType.BYTE_ARRAY);
uploadField.addListener(new Listener(){
#Override
public void componentEvent(Event event)
{
showUploadedImage(uploadField);
}
});
layout.addComponent(uploadField);
layout.addComponent(image);
}
private void showUploadedImage(UploadField upload) {
Object value = upload.getValue();
final byte[] data = (byte[]) value;
StreamResource resource = new StreamResource(
new StreamResource.StreamSource() {
#Override
public InputStream getStream() {
return new ByteArrayInputStream(data);
}
}, "filename.png");
image.setSource(resource);
}
Produces (after choosing a .png file):
Of course you may want to change type of uploadField listener to more specific one.
Tested on Java 8, Vaadin 7.4.1, Eclipse Luna.

Resources