I am trying to add image to pdf using iText with A4 page properties:
com.itextpdf.text.Document document = new com.itextpdf.text.Document(
com.itextpdf.text.PageSize.A4);
PdfWriter.getInstance(document, new FileOutputStream(m_pathToCreateFileIn + "my_web.pdf"));
System.out.println("New pdf -> " + m_pathToCreateFileIn + "my_web.pdf");
document.open();
Image image = Image.getInstance(pngPath);
image.scaleToFit(com.itextpdf.text.PageSize.A4.getWidth(), com.itextpdf.text.PageSize.A4.getHeight());
document.add(image);
I set both document and Image to A4 page size and still the image does not fit my document page size.
Thank you for any help.
You have to add document.newPage() before your changes will take effect, because you can't change the current page. Try:
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(m_pathToCreateFileIn + "my_web.pdf"));
document.open();
Image image = Image.getInstance(pngPath);
image.scaleToFit(PageSize.A4);
document.setPageSize(PageSize.A4);
document.newPage();
document.add(image);
document.close();
I know this is super late to the party, but I wanted to extend on the answer from #DonKanallie a bit (which was super helpful btw) to be a bit more flexibly in dealing with images of different sizes/dimensions. As the original poster mentioned, my Image was not fitting properly in an A4 output, hence the size of the image taken into consideration and the custom rectangle below
Document document = new Document();
FileOutputStream fos = new FileOutputStream(outputPath);
Image image = Image.getInstance(inputFile);
//Get Size of Original Image for conversion
float origWidth = image.getWidth();
float origHeight = image.getHeight();
image.scaleToFit(origWidth,origHeight);
//Set position of image in top left corner
image.setAbsolutePosition(0,0);
//Create Rectangle in support of new page size
Rectangle rectangle = new Rectangle(origWidth,origHeight);
PdfWriter writer = PdfWriter.getInstance(document, fos);
writer.open();
document.open();
//Set page size before adding new page
document.setPageSize(rectangle);
document.newPage();
document.add(image);
document.close();
writer.close();
Try to adjust parameters by x and y axis using this methods.
String imageUrl1 = "";
Image image1 = Image.getInstance(new URL(imageUrl1));
image1.scaleAbsolute(140, 190);
image1.setAbsolutePosition(450, 580);
document.add(image1);
Related
I am trying to read one PDF and copy its data into another PDF. The first PDF contains some text and images and I wish to write an image in the second PDF exactly where the text ends(which is basically the end of the PDF file). RIght now it just prints at the top. How can I make this change?
PdfReader reader = null;
reader = new PdfReader(Var.input);
Document document=new Document();
PdfWriter writer = null;
writer = PdfWriter.getInstance(document,new FileOutputStream(Var.output));
PdfImportedPage page = writer.getImportedPage(reader, 1);
reader.close();
document.open();
PdfContentByte cb = writer.getDirectContent();
// Copy first page of existing PDF into output PDF
document.newPage();
cb.addTemplate(page, 0, 0);
// Add your new data / text here
Image image = null;
image = Image.getInstance (Var.qr);
document.add(image);
document.close();
Try this:
First get the location/co-ords of where the image needs to go, then simply add the second line from below to your code so the image is inserted at that location "X, Y"
Image image = Image.getInstance(String RESOURCE);
image.setAbsolutePosition(X, Y);
writer.getDirectContent().addImage(image);
Take a look here for some examples in iText 5: https://itextpdf.com/en/resources/examples/itext-5-legacy/chapter-3-adding-content-absolute-positions
You should use a PdfStamper instead of a PdfWriter with imported pages. Your approach throws away all interactive contents. You can use sorifiend's idea there, too.
To determine where the text on the given page ends, have a look at the iText in Action, 2nd edition example ShowTextMargins which parses a PDF and ads a rectangle showing the text margin.
I want to move text with iText7. I have a source bounding box, that can be somewhere on the page and I have a target bounding box, that has a fixed position (incl. width and height). I'll stay on the same page. The source and target boxes can overlap. The source bounding box can also be larger than the target box. In this case I have to reduce the font size. The text should retain font, color and so on.
There is a cut and paste example on the iText website . But in the result pdf file you can select the text at the new and old position (tried it only with a normal pdf reader). I don't want the text to be selectable at the old position.
I thought, that maybe I could select the text and just place it at the new position and remove it from the old position. For the latter i would need pdfSweep, but this is ok. Adding the text at the new position should be no problem. Even if the text has different fonts, sizes and so on. There are plenty of examples on the iText website. The only way I know to select the text is like shown in this example. This gives me only the text. But to place it at the target position with the same font, color and so on, I need all those informations, too.
I know, that pdf is not meant for editing. This is often mention in answers on StackOverflow.
Is there a way to do this with iText7?
There is no high level API in iText allowing you to move page content, in particular not all content from some rectangle. One reason may be that in general this is no mere moving. PDFs often contain structures influencing larger areas, and such structures would not simply have to be moved but instead copied, and each copy restricted to its area.
It is indeed possible, though, to combine the cut and paste example the OP found with the pdfSweep module already considered by the OP to a solution which prevents the text from being selectable at the old position, e.g. like this:
public void moveCleanSection(PdfReader pdfReader, String targetFile, int page, Rectangle from, Rectangle to) throws IOException
{
LicenseKey.loadLicenseFile("itextkey-multiple-products.xml");
ByteArrayOutputStream interimMain = new ByteArrayOutputStream();
ByteArrayOutputStream interimPage = new ByteArrayOutputStream();
ByteArrayOutputStream interimSection = new ByteArrayOutputStream();
try ( PdfDocument pdfMainDocument = new PdfDocument(pdfReader);
PdfDocument pdfPageDocument = new PdfDocument(new PdfWriter(interimPage)) )
{
pdfMainDocument.setCloseReader(false);
pdfMainDocument.copyPagesTo(page, page, pdfPageDocument);
}
try ( PdfDocument pdfMainDocument = new PdfDocument(pdfReader, new PdfWriter(interimMain));
PdfDocument pdfSectionDocument = new PdfDocument(new PdfReader(new ByteArrayInputStream(interimPage.toByteArray())),
new PdfWriter(interimSection)) )
{
List<PdfCleanUpLocation> cleanUpLocations = new ArrayList<PdfCleanUpLocation>();
cleanUpLocations.add(new PdfCleanUpLocation(page, from, null));
cleanUpLocations.add(new PdfCleanUpLocation(page, to, null));
PdfCleanUpTool cleaner = new PdfCleanUpTool(pdfMainDocument, cleanUpLocations);
cleaner.cleanUp();
cleanUpLocations = new ArrayList<PdfCleanUpLocation>();
Rectangle mediaBox = pdfSectionDocument.getPage(1).getMediaBox();
if (from.getTop() < mediaBox.getTop())
cleanUpLocations.add(new PdfCleanUpLocation(1, new Rectangle(mediaBox.getLeft(), from.getTop(), mediaBox.getWidth(), mediaBox.getTop() - from.getTop()), null));
if (from.getBottom() > mediaBox.getBottom())
cleanUpLocations.add(new PdfCleanUpLocation(1, new Rectangle(mediaBox.getLeft(), mediaBox.getBottom(), mediaBox.getWidth(), from.getBottom() - mediaBox.getBottom()), null));
if (from.getLeft() > mediaBox.getLeft())
cleanUpLocations.add(new PdfCleanUpLocation(1, new Rectangle(mediaBox.getLeft(), mediaBox.getBottom(), from.getLeft() - mediaBox.getLeft(), mediaBox.getHeight()), null));
if (from.getRight() < mediaBox.getRight())
cleanUpLocations.add(new PdfCleanUpLocation(1, new Rectangle(from.getRight(), mediaBox.getBottom(), mediaBox.getRight() - from.getRight(), mediaBox.getHeight()), null));
cleaner = new PdfCleanUpTool(pdfSectionDocument, cleanUpLocations);
cleaner.cleanUp();
}
try ( PdfDocument pdfSectionDocument = new PdfDocument(new PdfReader(new ByteArrayInputStream(interimSection.toByteArray())));
PdfDocument pdfMainDocument = new PdfDocument(new PdfReader(new ByteArrayInputStream(interimMain.toByteArray())), new PdfWriter(targetFile)) )
{
float scale = Math.min(to.getHeight() / from.getHeight(), to.getWidth() / from.getWidth());
pdfSectionDocument.getPage(1).setMediaBox(from);
PdfFormXObject pageXObject = pdfSectionDocument.getFirstPage().copyAsFormXObject(pdfMainDocument);
PdfPage pdfPage = pdfMainDocument.getPage(page);
PdfCanvas pdfCanvas = new PdfCanvas(pdfPage);
pdfCanvas.addXObject(pageXObject, scale, 0, 0, scale, (to.getLeft() - from.getLeft() * scale), (to.getBottom() - from.getBottom() * scale));
}
}
(From MoveSectionCleanly.java)
Beware: Due to the nature of pdfSweep, text being on the border of the source area is removed both from the source and the copy of it.
I am generating charts using jfreechart.Now as per my requirement i need to export that chart into pdf using itext in java.Here i am able to export jfreechart to pdf but it is coming at the bottom of the pdf file whereas i want it to be top.
Here is my code..
PdfWriter writer = null;
Document document = new Document();
try {
writer = PdfWriter.getInstance(document, new FileOutputStream(
fileName));
document.open();
PdfContentByte contentByte = writer.getDirectContent();
PdfTemplate template = contentByte.createTemplate(width, height);
Graphics2D graphics2d = template.createGraphics(width, height,
new DefaultFontMapper());
Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width,
height);
chart.draw(graphics2d, rectangle2d);
graphics2d.dispose();
contentByte.addTemplate(template, 0, 0);
How to set PdfWriter to write at the top of the pdf file.Please help me.
You are adding the template at the bottom of the page:
contentByte.addTemplate(template, 0, 0);
There are different options you can choose from.
You can add the template at another coordinate:
contentByte.addTemplate(template, 36, 400);
This will add the document at position x = 36 and y = 400. In this case, you need to do your math: instead of 400, you should take the top coordinate of the page (e.g. y = 842) minus a margin (e.g. 36) minus the height of the image.
If can be easier to choose a different option:
Image img = Image.getInstance(template);
document.add(img);
Now you're template is added in the flow of the document, just like all other high-level objects (just like Paragraphs and PdfPTables).
I am trying to read one PDF and copy its data into another PDF. The first PDF contains some text and images and I wish to write an image in the second PDF exactly where the text ends(which is basically the end of the PDF file). RIght now it just prints at the top. How can I make this change?
PdfReader reader = null;
reader = new PdfReader(Var.input);
Document document=new Document();
PdfWriter writer = null;
writer = PdfWriter.getInstance(document,new FileOutputStream(Var.output));
PdfImportedPage page = writer.getImportedPage(reader, 1);
reader.close();
document.open();
PdfContentByte cb = writer.getDirectContent();
// Copy first page of existing PDF into output PDF
document.newPage();
cb.addTemplate(page, 0, 0);
// Add your new data / text here
Image image = null;
image = Image.getInstance (Var.qr);
document.add(image);
document.close();
Try this:
First get the location/co-ords of where the image needs to go, then simply add the second line from below to your code so the image is inserted at that location "X, Y"
Image image = Image.getInstance(String RESOURCE);
image.setAbsolutePosition(X, Y);
writer.getDirectContent().addImage(image);
Take a look here for some examples in iText 5: https://itextpdf.com/en/resources/examples/itext-5-legacy/chapter-3-adding-content-absolute-positions
You should use a PdfStamper instead of a PdfWriter with imported pages. Your approach throws away all interactive contents. You can use sorifiend's idea there, too.
To determine where the text on the given page ends, have a look at the iText in Action, 2nd edition example ShowTextMargins which parses a PDF and ads a rectangle showing the text margin.
I have a an SWT image I want to export this image into a pdf file using iText API.
I have tried saving this image on the disk and then using the path of image to export
it to the pdf, this takes lots of time to generate the pdf.
I have also tried converting the SWT image into AWT image and then exporting it into the
pdf, this approach takes even more time to generate pdf.
Another approach I have been trying is to convert the raw data of image into
jpeg byteArrayOutputStream using ImageLoader Object as shown below :
ImageLoader tempLoader = new ImageLoader();
tempLoader.data = new ImageData[] {
image.getImageData()
};
ByteArrayOutputStream bos = new ByteArrayOutputStream();
tempLoader.save(bos, SWT.IMAGE_JPEG);
Now I am using this ByteArrayOutputStream as input to
OutputStream outStream = new FileOutputStream(selectedPathAndName);
Document document = new Document();
document.setMargins(0,0,0,0);
document.setPageSize(new Rectangle(0,0,width,height));
PdfWriter.getInstance(document, outStream);
document.open();
com.itextpdf.text.Image pdfImage = com.itextpdf.text.Image.getInstance(bos.toByteArray());
document.add(pdfImage);
document.close();
This generates pdf files with the width and height I have set, but the page seems to be empty.
Any suggestions or any other approach is most welcome.
Thank you,
It looks your page sizes are zero, try setting them to something like A4 in the constructor.
Document document = new Document(PageSize.A4, 50, 50, 50, 50);