How can I add a password to a base 64 pdf? - java

I have this method in which I add a password to the pdf, but I am doing it with pdf from the computer. What I want to try is to receive as input parameter a string that would be pdf in base 64 and respond to a base64.
public static void main(String[] args) {
try {
OutputStream file = new FileOutputStream(new File("D:\\Test.pdf"));
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, file);
writer.setEncryption(USER_PASS.getBytes(), OWNER_PASS.getBytes(),
PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
document.open();
document.add(new Paragraph("Hello World, iText"));
document.add(new Paragraph(new Date().toString()));
document.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}

It was complicated how to handle a Base64 pdf because it was the first time, but in the end I was able to develop the method where you can add the password to a pdf that is already in base64.
public String EncriptarPDFconContraseña(String pdfBase64, String passwordUser, String passwordOwner) throws IOException, DocumentException {
PdfReader reader = new PdfReader(Base64.decode(pdfBase64));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, baos);
stamper.setEncryption(passwordUser.getBytes(), passwordOwner.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
stamper.close();
String base64 = Base64.encodeBytes(baos.toByteArray());
return base64;
}

Related

Create pdf java from base64

I am exploring usage of iText maven dependency to generate a pdf from the below code.
try {
Document document = new Document();
OutputStream outputStream =
new FileOutputStream(new File("C:\\ImageTester\\samplePDF.pdf"));
PdfWriter.getInstance(document, outputStream);
//Open the document
document.open();
document.add(new Paragraph("Hello world ");
//Close document and outputStream.
document.close();
outputStream.close();
System.out.println("Pdf created successfully.");
} catch (Exception e) {
e.printStackTrace();
}
Maven:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
This above works fine and generate the PDF. However, I have a use-case where I am sent Base64 encoded String that needs to be saved as PDF. How do I this? Converting the Base64 to a byte array and writing that to the outputStream generates the a corrupted PDF.
byte[] bytes = Base64.getDecoder().decode(b64String);
outputStream.write(bytes);
PdfWriter.getInstance(document, outputStream);

Unable to read PDF using itextpdf

I am using itextpdf-5.5.4 jar to merge or add two pdf into one PDF.
I did not get any error or exception while running code but displayed below text in Merged PDF. I did not get below text when i open individual PDF's.
The document you are trying to load requires Adobe Reader 8 or higher.
You may not have the Adobe Reader installed or your viewing
environment may not be properly configured to use Adobe Reader.
For information on how to install Adobe Reader and configure your
viewing environment please see
http://www.adobe.com/go/pdf_forms_configure.
void mergePdfFiles(List<InputStream> inputPdfList, OutputStream outputStream) throws Exception {
// Create document and pdfReader objects.
Document document = new Document();
List<PdfReader> readers = new ArrayList<PdfReader>();
int totalPages = 0;
// Create pdf Iterator object using inputPdfList.
Iterator<InputStream> pdfIterator = inputPdfList.iterator();
// Create reader list for the input pdf files.
while (pdfIterator.hasNext()) {
InputStream pdf = pdfIterator.next();
PdfReader pdfReader = new PdfReader(pdf);
readers.add(pdfReader);
totalPages = totalPages + pdfReader.getNumberOfPages();
}
// Create writer for the outputStream
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
// Open document.
document.open();
// Contain the pdf data.
PdfContentByte pageContentByte = writer.getDirectContent();
PdfImportedPage pdfImportedPage;
int currentPdfReaderPage = 1;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
// Iterate and process the reader list.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
// Create page and add content.
while (currentPdfReaderPage <= pdfReader.getNumberOfPages()) {
document.newPage();
pdfImportedPage = writer.getImportedPage(pdfReader, currentPdfReaderPage);
pageContentByte.addTemplate(pdfImportedPage, 0, 0);
currentPdfReaderPage++;
}
currentPdfReaderPage = 1;
}
// Close document and outputStream.
outputStream.flush();
document.close();
outputStream.close();
System.out.println("Pdf files merged successfully.");
}
public static void main(String args[]) {
try {
List<InputStream> inputPdfList = new ArrayList<InputStream>();
inputPdfList.add(new FileInputStream("pdf1.pdf"));
inputPdfList.add(new FileInputStream("pdf2.pdf"));
OutputStream outputStream = new FileOutputStream("Merge-PDF.pdf");
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
mergePdfFiles(inputPdfList, byteStream);
byte[] byteS = byteStream.toByteArray();
outputStream.write(byteS);
} catch (Exception e) {
e.printStackTrace();
}
}
Please help me out on this.

iTextPDF - Unable to convert HTML to PDF

I am building a Java web service application in which I would like to convert the HTML file to PDF and send an email to a particular email address.
Conversion from XHTML to PDF.
try {
File outputFile = new File("D:\\Files\\Output_Files\\" + System.currentTimeMillis() + ".pdf");
OutputStream file = new FileOutputStream(outputFile);
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, file);
document.open();
InputStream is = new ByteArrayInputStream(htmlString.getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document,is);
document.close();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
I have verified htmlString and it holds an exact HTML string.
Please review my HTML content here
The issue is that I am receiving the PDF but it does not have any content but an empty page.

How can I merge the documents consisting PDFs as well as images?

In my current code I am merging the documents consisting PDF files.
public static void appApplicantDownload(File file) {
Connection con = getConnection();
Scanner sc = new Scanner(System.in);
List < InputStream > list = new ArrayList < InputStream > ();
try {
OutputStream fOriginal = new FileOutputStream(file, true); // original
list.add(new FileInputStream(file1));
list.add(new FileInputStream(file2));
list.add(new FileInputStream(file3));
doMerge(list, fOriginal);
} catch (Exception e) {
}
}
public static void doMerge(List < InputStream > list, OutputStream outputStream) throws DocumentException, IOException {
try {
System.out.println("Merging...");
Document document = new Document();
PdfCopy copy = new PdfCopy(document, outputStream);
document.open();
for (InputStream in : list) {
ByteArrayOutputStream b = new ByteArrayOutputStream();
IOUtils.copy( in , b);
PdfReader reader = new PdfReader(b.toByteArray());
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
copy.addPage(copy.getImportedPage(reader, i));
}
}
outputStream.flush();
document.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
But now I want to change the code such that it should allow Image as well as PDFs to be merged. Above code is giving me the error that No PDF Signature found
First, you have to know somehow if the file is a PDF or an image. The easiest way would be to use the extension of the file. So you would have get extension of the file and then pass this information to your doMerge method. Do achieve that, I would change your current method
public static void doMerge(List<InputStream> list, OutputStream outputStream)
For something like
public static void doMerge(Map<InputStream, String> files, OutputStream outputStream)
So each InputStream is associated with a extension.
Second, you have to load images and pdf seperately. So your loop should look like
for (InputStream in : files.keySet()) {
String ext = files.get(in);
if(ext.equalsIgnoreCase("pdf"))
{
//load pdf here
}
else if(ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg"))
{
//load image here
}
}
In java, you can easily load an Image using ImageIO. Look at this question for more details on this topic: Load image from a filepath via BufferedImage
Then to add your image into the PDF, use the PdfWriter
PdfWriter pw = PdfWriter.GetInstance(doc, outputStream);
Image img = Image.GetInstance(inputStream);
doc.Add(img);
doc.NewPage();
If you want to convert your image into PDF before and merge after you also can do that but you just have to use the PdfWriter to write them all first.
Create a new page in the opened PDF document and use the function for inserting images to place the image on that page.

How to get the OutputStream of a written PDF from iText

I need your help in getting and storing the written PDF from iText in an OutputStream and then to convert it to an InputStream.
The code of writing the PDF is below:
public void CreatePDF() throws IOException {
try{
Document doc = new Document(PageSize.A4, 50, 50, 50, 50);
OutputStream out = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(doc, out);
doc.open();
PdfPTable table = new PdfPTable(1);
PdfPCell cell = new PdfPCell(new Phrase("First PDF"));
cell.setBorder(Rectangle.NO_BORDER);
cell.setRunDirection(PdfWriter.RUN_DIRECTION_LTR);
table.addCell(cell);
doc.add(table);
doc.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
So I am seeking your help to write that PDF in an OutputStream and then to convert it to InputStream.
I need to get the InputStream value so I can pass it to the line for the file download:
StreamedContent file = new DefaultStreamedContent(InputStream, "application/pdf", "xxx.pdf");
Updated Jon Answer:
public InputStream createPdf1() throws IOException {
Document doc = new Document(PageSize.A4, 50, 50, 50, 50);
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfWriter writer;
try {
writer = PdfWriter.getInstance(doc, out);
} catch (DocumentException e) {
}
doc.open();
PdfPTable table = new PdfPTable(1);
PdfPCell cell = new PdfPCell(new Phrase("First PDF"));
cell.setBorder(Rectangle.NO_BORDER);
cell.setRunDirection(PdfWriter.RUN_DIRECTION_LTR);
table.addCell(cell);
doc.add(table);
}
catch ( Exception e)
{
e.printStackTrace();
}
return new ByteArrayInputStream(out.toByteArray());
}
You should change the declaration of out to be of type ByteArrayOutputStream rather than just OutputStream. Then you can call ByteArrayOutputStream.toByteArray() to get the bytes, and construct a ByteArrayInputStream wrapping that.
As an aside, I wouldn't catch Exception like that, and I'd use a try-with-resources statement to close the document, assuming it implements AutoCloseable. It's also a good idea to follow Java naming conventions. So for example, you might have:
public InputStream createPdf() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (Document doc = new Document(PageSize.A4, 50, 50, 50, 50)) {
PdfWriter writer = PdfWriter.getInstance(doc, out);
doc.open();
PdfPTable table = new PdfPTable(1);
PdfPCell cell = new PdfPCell(new Phrase("First PDF"));
cell.setBorder(Rectangle.NO_BORDER);
cell.setRunDirection(PdfWriter.RUN_DIRECTION_LTR);
table.addCell(cell);
doc.add(table);
}
return new ByteArrayInputStream(out.toByteArray());
}

Categories