How to Insert Boxable Table Between Prexisting Header and Footer of PDF File - pdfbox

In Adobe Acrobat Pro DC, I have created a PDF document with a header and footer. I'm using PDFBox and Boxable to put a table between the header and footer. This works on the first page of the document. But, when my Boxable table spans several pages, the header and footer only appear on the first page. They are absent from the second page, third page, etc.
I'm using this PageContentStream constructor:
PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, true);
Below is how I'm loading the template file and creating the table. Thanks!
File pdfFile = pdfUtil.getPdfFile("pdf/table.pdf");
PDDocument document = PDDocument.load(pdfFile);
PDPage page = document.getPage(0);
PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, false, true);
// Some code here to set variables
BaseTable table = new BaseTable(yPosition, yStartNewPage, bottomMargin, tableWidth, margin, document, page, true, drawContent);

Related

How to create PDF/UA in iText7 with text hyperlink

I am trying to create a PDF/UA compliant file that contains a text hyperlink with iText 7. Both the Acrobat Preflight test for PDF/UA and the PDF Accessibility Checker (PAC 3) complain that the PDF file say that the PDF is not compliant.
PAC 3 says ""Link" annotation is not nested inside a "Link" structure element" and the Acrobat Preflight test says the Link annotation does not have an alternate description in the Contents key.
The following is my attempt to create PDF/UA compliant output that contains a text hyperlink.
Any advice would be appreciated.
public void testHyperLink() throws IOException {
// Create PDF/UA with text hyperlink
String filename = "./results/HyperLink.pdf";
WriterProperties properties = new WriterProperties();
properties.addUAXmpMetadata().setPdfVersion(PdfVersion.PDF_1_7);
PdfWriter writer = new PdfWriter(filename, properties);
pdfDoc = new PdfDocument(writer);
//Make document tagged
pdfDoc.setTagged();
pdfDoc.getCatalog().setLang(new PdfString("en-US"));
pdfDoc.getCatalog().setViewerPreferences(new PdfViewerPreferences().setDisplayDocTitle(true));
PdfDocumentInfo info = pdfDoc.getDocumentInfo();
info.setTitle("Hello Hyperlinks!");
document = new Document(pdfDoc);
// Must embed font for PDF/UA
byte[] inputBytes = Files.readAllBytes(Paths.get("./resources/fonts/opensans-regular.ttf"));
boolean embedded = true;
boolean cached = false;
PdfFont font = PdfFontFactory.createFont(inputBytes, PdfEncodings.CP1252, embedded, cached);
Text text = new Text("This is a Text link");
text.setFont(font);
text.setFontSize(16F);
// Add alternate text for hyperlink
text.getAccessibilityProperties().setAlternateDescription("Click here to go to the iText website");
PdfAction act = PdfAction.createURI("https://itextpdf.com/");
text.setAction(act);
Paragraph para = new Paragraph();
para.add(text);
document.add(para);
document.close();
System.out.println("Created "+ filename);
}
A Link object might be what you want:
Link lnk = new Link("This is a Text link",
PdfAction.CreateURI("https://itextpdf.com/"));
lnk.SetFont(font);
lnk.GetLinkAnnotation().SetBorder(new PdfAnnotationBorder(0, 0, 0));//Remove the default border
lnk.GetAccessibilityProperties().SetAlternateDescription("Click here to go to the iText website");
Paragraph para = new Paragraph();
para.Add(lnk);
document.Add(para);

Unable to create PDF from JSPDF

Save in DB and import data and create a pdf file using jspdf.
Data is stored up to html tag...
select ct_contents from contract where ct_id = 659;
RESULT : `<p style="text-align:justify"><span style="font-size:10.5pt"><span style="font-family:Century,serif"><span style="font-family:"MS Mincho"">氏  名</span></span></span></p>`
I have this js code :
let pdfName = this.newTemplate.tp_title.trim()
var doc = new jsPDF();
doc.addFileToVFS('NotoSansCJKjp-Regular.ttf', VFS);
doc.addFont('NotoSansCJKjp-Regular.ttf', 'NotoSansCJKjp', 'Bold');
doc.setFont('NotoSansCJKjp', 'Bold');
doc.setFontSize(12);
var paragraph = this.contract.ct_contents;
var lines = doc.splitTextToSize(paragraph, 150);
doc.text(15, 60, lines);
doc.save(pdfName + '.pdf');
add a font to work on it, but check the downloaded pdf, the html tag will also appear.
I want to remove this tag and make it appear only in text.
image is the result of downloading by pdf.
And it is page 3 in ms word and only page 1 of pdf is download.....
How can I get the font to come out without getting the html tag?

Generate PDF from gsp page

I am using grails 2.5.2.
I have created a table which shows all the data from database to gsp page and now i need to save that shown data in a pdf format with a button click.What will be the best way to show them into a PDF and save it to my directory. please Help
You can use itext for converting HTML into pdf using the code below:
public void createPdf(HttpServletResponse response, String args, String css, String pdfTitle) {
response.setContentType("application/force-download")
response.setHeader("Content-Disposition", "attachment;filename=${pdfTitle}.pdf")
Document document = new Document()
Rectangle one = new Rectangle(900, 600)
document.setPageSize(one)
PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream())
document.open()
ByteArrayInputStream bis = new ByteArrayInputStream(args.toString().getBytes())
ByteArrayInputStream cis = new ByteArrayInputStream(css.toString().getBytes())
XMLWorkerHelper.getInstance().parseXHtml(writer, document, bis, cis)
document.close()
}
Though answering this question late,take a look at grails export plugin.It will be useful if you want to export your data to excel and pdf( useful only if there is no in pre-defined template to export).
Got idea from itext. Used itext 2.1.7 and posted all the values to pdf from a controller method. Used images as background and paragraph and phrase to show values from database.

Text split and duplicating : Itext

I'm using iText library for generating PDFs where I have a table that spans across pages. In order to continue my text splits across pages, i'v used setSplitLate as false. In some generated PDFs, last line of page 1 gets repeated in first line of page 2.
Is there any property that needs to be set to avoid duplication of lines across pages?
e.g. code
Document document = new Document(PageSize.A4, 0, 0,0, 45);
document.open();
PdfWriter writer;
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100);
table.setSplitLate(false);
//added stuff in table
document.add(table);
adding footer in onEndPage():
PdfPTable footer = new PdfPTable(1);
footer.setTotalWidth(595);
PdfPCell footerCell = new PdfPCell();
footerCell.setPaddingTop(10f);
footerCell.setBorder(Rectangle.NO_BORDER);
footer.addCell(footerCell);
footer.writeSelectedRows(0, -1, 0, document.bottom(), writer.getDirectContent());

How to exactly position an Image inside an existing PDF page using PDFBox?

I am able to insert an Image inside an existing pdf document, but the problem is,
The image is placed at the bottom of the page
The page becomes white with the newly added text showing on it.
I am using following code.
List<PDPage> pages = pdDoc.getDocumentCatalog().getAllPages();
if(pages.size() > 0){
PDJpeg img = new PDJpeg(pdDoc, in);
PDPageContentStream stream = new PDPageContentStream(pdDoc,pages.get(0));
stream.drawImage(img, 60, 60);
stream.close();
}
I want the image on the first page.
PDFBox is a low-level library to work with PDF files. You are responsible for more high-level features. So in this example, you are placing your image at (60, 60) starting from lower-left corner of your document. That is what stream.drawImage(img, 60, 60); does.
If you want to move your image somewhere else, you have to calculate and provide the wanted location (perhaps from dimensions obtained with page.findCropBox(), or manually input your location).
As for the text, PDF document elements are absolutely positioned. There are no low-level capabilities for re-flowing text, floating or something similar. If you write your text on top of your image, it will be written on top of your image.
Finally, for your page becoming white -- you are creating a new content stream and so overwriting the original one for your page. You should be appending to the already available stream.
The relevant line is:
PDPageContentStream stream = new PDPageContentStream( pdDoc, pages.get(0));
What you should do is call it like this:
PDPageContentStream stream = new PDPageContentStream( pdDoc, pages.get(0), true, true);
The first true is whether to append content, and the final true (not critical here) is whether to compress the stream.
Take a look at AddImageToPDF sample available from PDFBox sources.
Try this
doc = PDDocument.load( inputFileName );
PDXObjectImage ximage = null;
ximage = new PDJpeg(doc, new FileInputStream( image )
PDPage page = (PDPage)doc.getDocumentCatalog().getAllPages().get(0);
PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
contentStream.drawImage( ximage, 425, 675 );
contentStream.close();
This prints the image in first page. If u want to print in all pages just put on a for loop with a condition of number of pages as the limit.
This worked for me well!
So late answer but this is for who works on it in 2020 with Kotlin: drawImage() is getting float values inside itself so try this:
val file = File(getPdfFile(FILE_NAME))
val document = PDDocument.load(file)
val page = document.getPage(0)
val contentStream: PDPageContentStream
contentStream = PDPageContentStream(document, page, true, true)
// Define a content stream for adding to the PDF
val bitmap: Bitmap? = ImageSaver(this).setFileName("sign.png").setDirectoryName("signature").load()
val mediaBox: PDRectangle = page.mediaBox
val ximage: PDImageXObject = JPEGFactory.createFromImage(document, bitmap)
contentStream.drawImage(ximage, mediaBox.width - 4 * 65, 26f)
// Make sure that the content stream is closed:
contentStream.close()
// Save the final pdf document to a file
pdfSaveLocation = "$directoryPDF/$UPDATED_FILE_NAME"
val pathSave = pdfSaveLocation
document.save(pathSave)
document.close()
I am creating a new PDF and running below code in a loop - to add one image per page and below co-ordinates and height and width values work well for me.
where out is BufferedImage reference variable
PDPage page = new PDPage();
outputdocument.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(outputdocument, page, AppendMode.APPEND, true);
PDImageXObject pdImageXObject = JPEGFactory.createFromImage(outputdocument, out);
contentStream.drawImage(pdImageXObject, 5, 2, 600, 750);
contentStream.close();
This link gives you details about Class PrintImageLocations.
This PrintImageLocations will give you the x and y coordinates of the images.
Usage: java org.apache.pdfbox.examples.util.PrintImageLocations input-pdf