PDFbox set visible when printing - java

I am working with PDFBOX and the documentation on it seems sparse so I've come here for some help. I am trying to print out a pdf form that I've created, with fields populated dynamically by eclipse. I can get it to import and print, but when I do print, the fields I've set don't show up (although they do when I save it to HDD). Can someone point me to the settings to set visible when printing? I saw itext had something similar, and I'm hoping that PDFBox does too.
Here is my current code.
PDDocument doc = null;
try{
doc = PDDocument.load("resources/orderForm.pdf");
PDDocumentCatalog docCatalog = doc.getDocumentCatalog();
PDAcroForm acroForm = docCatalog.getAcroForm();
PDField field = acroForm.getField("Orderer");
field.setValue("JohnTest");
} catch (IOException ie){
System.out.println(ie);
}
//doc.addPage(new PDPage());
try{
//doc.save("Empty PDF.pdf");
doc.silentPrint();
//doc.print();
doc.close();
} catch (Exception io){
System.out.println(io);
}
}

found my answer, can't use pdfbox to do it, although the alternative is just as simple. Use the desktop to print the file! example code as follows
public void printOrder(){
try {
File myFile = new File(finished);
//Desktop.getDesktop().open(myFile);
Desktop.getDesktop().print(myFile);
doc.close();
} catch (IOException ex) {
// no application registered for PDFs
}
}

Related

How print PDF document with user setting?

I am trying to print a pdf document using java.awt.print.PrinterJob.print (PrintRequestAttributeSet attributes). Before that, I put the necessary attributes in attributes using PrinterJob.printerDialog (attributes) and they really get there, but from everything I've tried, only the change in the number of pages that will be printed has been applied. The rest of the settings are ignored. How can I get the printer to print with the settings I want?
pdfReport - byte[] which was obtained with DatatypeConverter.parseBase64Binary from
printerService - standart "Microsoft Print to PDF"
PDDocument document = PDDocument.load(pdfReport);
try {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(printer.printerService);
HashPrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
if (job.printDialog(attributes)) {
try {
job.print(attributes);
} catch (PrinterException e) {
System.out.println(e);
}
}
} finally {
document.close();
}
P.S. : when the program is running, sun.awt.windows.WPrinterJob is used as the PrinterJob implemenjatation

apache pdfbox - how to test if a document is flattened?

I have written the following small Java main method. It takes in a (hardcoded for testing purposes!) PDF document I know contains active elements in the form and need to flatten it.
public static void main(String [] args) {
try {
// for testing
Tika tika = new Tika();
String filePath = "<path-to>/<pdf-document-with-active-elements>.pdf";
String fileName = filePath.substring(0, filePath.length() -4);
File file = new File(filePath);
if (tika.detect(file).equalsIgnoreCase("application/pdf")) {
PDDocument pdDocument = PDDocument.load(file);
PDAcroForm pdAcroForm = pdDocument.getDocumentCatalog().getAcroForm();
if (pdAcroForm != null) {
pdAcroForm.flatten();
pdAcroForm.refreshAppearances();
pdDocument.save(fileName + "-flattened.pdf");
}
pdDocument.close();
}
}
catch (Exception e) {
System.err.println("Exception: " + e.getLocalizedMessage());
}
}
What kind of test would assert the File(<path-to>/<pdf-document-with-active-elements>-flattened.pdf) generated by this code would, in fact, be flat?
What kind of test would assert that the file generated by this code would, in fact, be flat?
Load that document anew and check whether it has any form fields in its PDAcroForm (if there is a PDAcroForm at all).
If you want to be thorough, also iterate through the pages and assure that there are no Widget annotations associated to them anymore.
And to really be thorough, additionally determine the field positions and contents before flattening and apply text extraction at those positions to the flattened pdf. This verifies that the form has not merely been dropped but indeed flattened.

IText html to pdf wrapping line

Hello I'm creating javafx app with iText. I have html editor to write text and I want to create pdf from it. Everything works but when I have a really long line that is wrapped in html editor, in pdf it isn't wrapped, its out of page, how can I set wrapping page? here is my code:
PdfWriter writer = null;
try {
writer = new PdfWriter("doc.pdf");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Initialize PDF document
PdfDocument pdf = new PdfDocument(writer);
// Initialize document
Document document = new Document(pdf, PageSize.A4);
List<IElement> list = null;
try {
list = HtmlConverter.convertToElements(editor.getHtmlText());
} catch (IOException e) {
e.printStackTrace();
}
// add elements to document
for (IElement p : list) {
document.add((IBlockElement) p);
}
// close document
document.close();
I also want to set line spacing for this text
Thank you for help
I don't get any errors for the following code:
public class stack_overflow_0008 extends AbstractSupportTicket{
private static String LONG_PIECE_OF_TEXT =
"Once upon a midnight dreary, while I pondered, weak and weary," +
"Over many a quaint and curious volume of forgotten lore—" +
"While I nodded, nearly napping, suddenly there came a tapping," +
"As of some one gently rapping, rapping at my chamber door." +
"Tis some visitor,” I muttered, “tapping at my chamber door—" +
"Only this and nothing more.";
public static void main(String[] args)
{
PdfWriter writer = null;
try {
writer = new PdfWriter(getOutputFile());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Initialize PDF document
PdfDocument pdf = new PdfDocument(writer);
// Initialize document
Document document = new Document(pdf, PageSize.A4);
List<IElement> list = null;
try {
list = HtmlConverter.convertToElements("<p>" + LONG_PIECE_OF_TEXT + "</p>");
} catch (IOException e) {
e.printStackTrace();
}
for (IElement p : list) {
document.add((IBlockElement) p);
}
document.close();
}
}
The document is a single (A4) page PDF with one string neatly wrapped.
I think perhaps the content of your string is to blame?
Could you post the HTML you get from this editor object?
Update:
Using the code from this answer on the HTML shared in a new comment to the question, I get the following result:
As you can see, the content is distributed over two lines. No content "falls off the page."

iText not working outside netbeans

I wrote the following code in Netbeans editor in Java UI application for generating PDF using itext.
String result="";
Document doc=new Document();
PdfWriter writer=null;
DecimalFormat df=new DecimalFormat("0.00");
try
{
writer=PdfWriter.getInstance(doc, new FileOutputStream(new File("second.pdf")));
doc.addAuthor("abcdefg");
doc.addCreationDate();
doc.addProducer();
doc.addCreator("abcdefg");
doc.addTitle("Invoice for company");
doc.setPageSize(PageSize.A4);
doc.open();
doc.newPage();
doc.add(new Paragraph("new paragraph"));
PdfPTable table = new PdfPTable(1);
PdfPCell cellValue = new PdfPCell(new Phrase("Header 1"));
cellValue.setColspan(1);
table.addCell(cellValue);
doc.add(table);
result= "Successfully created preview.Please check the document";
}
catch(Exception e)
{
result= "Doucment already opened. Please close it";
System.out.println("exception came");
}
finally
{
if(doc!=null)
{
doc.close();
}
if(writer!=null)
{
writer.close();
}
return result;
}
This same piece of code is generating the pdf when I hit the RUN button in NetBeans but if double click the ".JAR" file in the project folder it is not able to add table to the pdf and generating the exception IOException Document has no pages.
There are two interesting things happening here :
1) When I remove the table adding part from my code, it is working very fine in in both the cases. This proves that "build" in netbeans is happening properly.
2) When I add the table part. The exception is generated but it is not executing the catch block and finally block. I am saying this because if catch and finally blocks are executed properly DOCUMENT will be definitely closed properly. But here when I double click the document when my app generated the file, it is showing that the FILE IS ALREADY IN USE AND IT IS DAMAGED FILE. This proves that the catch and finally blocks are not executing.

Updating an MSWord document with Apache POI

I'm trying to update a Microsoft Word document using Apache POI. The msword document is a template that contains a number of placeholders in the form "${place.holder}" and all I need to do is to replace the holders with specific values. What I've got so far is
private void start() throws FileNotFoundException, IOException {
POIFSFileSystem fsfilesystem = null;
HWPFDocument hwpfdoc = null;
InputStream resourceAsStream = getClass().getResourceAsStream("/path/to/document/templates/RMA FORM.doc");
try {
fsfilesystem = new POIFSFileSystem(resourceAsStream );
hwpfdoc = new HWPFDocument(fsfilesystem);
Range range = hwpfdoc.getRange();
range.replaceText("${rma.number}","08739");
range.replaceText("${customer.name}", "Roger Swann");
FileOutputStream fos = new FileOutputStream(new File("C:\\temp\\updatedTemplate.doc"));
hwpfdoc.write(fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The program runs without errors. If I look in the output file with a Hex editor I can see that the placeholders have been replaced by the program. However, when I try to open the document with MSWord, MSWord crashes.
Is there a step (series of steps) that I'm missing, or am I basically out of luck with this? Do I need to adjust any counters because the length of the replacement text is not the same as the length of the replaced text?
Regards
use new FileInputStream() instead of getClass().getResourceAsStream("/path/to/document/templates/RMA FORM.doc");

Categories

Resources