In Java, I have to crop and rotate an image in scanned pdf file and create another pdf file with the result image
For example, I have the image1 and want get the image2 centered in the page as result
How can I proceed?
Thanks!
The pdf is a scanned file.
It contains for example a student card.
I have to rotate the stutend card scanned on the right way and centered it in the A4 page.
I try to get the image like this :
PDDocument docIn = null;
File inputPdfFile = new File("C:\\test.pdf");
File output = new File("C:\\testOutput.png");
try {
// Read the pdf into a BufferedImage
docIn = PDDocument.load(inputPdfFile);
List<PDPage> pages = docIn.getDocumentCatalog().getAllPages();
PDPage page = pages.get(0);
// get the image
BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 300);
ImageIO.write(image, "png", output);
} catch (IOException e) {
e.printStackTrace();
}
Then, I use the javaxt librairies to trim the image
Image image = new Image(output);
image.trim();
image.saveAs("C:\\projetCrop\\trimImage.png");
Now, how to detect the rotation angle?
Related
I am using itext7 to create pdf file
,and at the footer I am trying to add png images as follows:
PdfDocumentEvent documentEvent = (PdfDocumentEvent) event;
PdfPage page = documentEvent.getPage();
PdfCanvas canvas = new PdfCanvas(page);
byte[] signature = null; // retrieved from database
PngImageData imageData = (PngImageData) ImageDataFactory.createPng(signature);
canvas.addImageAt(imageData, 5f, 25f, false);
the original image itself has good resolution, but when the image is added to the pdf it appears with poor quality although I am adding the image without any changes or scaling.
how can I improve the image quality in the final pdf ?
This is snippet of my code for adding image to PDF:
PdfContentByte cbLogo = writer.getDirectContent();
if (instanceSettings.getDocumentHeaderImageLocation() != null) {
try {
String encodedString = instanceSettings.getDocumentHeaderImageLocation();
byte[] decodedBytes = Base64
.getDecoder()
.decode(encodedString);
Image imgLogo = Image.getInstance(decodedBytes);
imgLogo.scaleToFit(220f, 150f);
imgLogo.setAbsolutePosition((writer.getPageSize().getWidth() / 4) - (imgLogo.getScaledWidth() / 2),
writer.getPageSize().getHeight() - imgLogo.getScaledHeight() - 30);
cbLogo.addImage(imgLogo);
} catch (Exception e){
ErrorHandler.handle(e);
}
}
And here is another:
Image qr = Image.getInstance(file.getAbsolutePath());
qr.scaleToFit(70f, 70f);
qr.setSpacingBefore(0);
qr.setSpacingAfter(0);
qr.setPaddingTop(0);
PdfPCell cell = new PdfPCell();
cell.setPadding(0f);
cell.setUseAscender(true);
cell.setUseDescender(true);
cell.addElement(qr);
Image is of type:
import com.itextpdf.text.Image;
You can give it a try with this code. For me, both works as expected but as I said in the comments, I sometimes have dificulties viewing it in PDF application. As far as I know, itext has nothing to do with it.
I'm trying to add a background in a PDF using Scalable Vector Graphics (.svg). Initially the recommended way was to transform the SVG into an Image object and then use scaleToFit to get it to the right size, then add it to the document. This works partially as it transforms the small and scalable SVG into a Bitmap. Next I've made a PdfFormXObject in order to get back the scaling by having it drawn on each page. However, now it does not display anything at all.
ByteArrayInputStream inputStream = new ByteArrayInputStream(backgroundBytes);
PdfFormXObject svg = SvgConverter.convertToXObject(inputStream, pdf);
PdfCanvas canvas = new PdfCanvas(pdf.getFirstPage());
Rectangle rect = new Rectangle(PageSize.A4.getWidth(), PageSize.A4.getHeight());
canvas.addXObject(svg, rect);
How should I be adding SVG backgrounds to iText 7 PDFs? Can this be done properly in the first place? I have not been able to find good code examples.
Update:
Here is the code for converting the SVG to a properly scaled Image. The issue with this is that it works for adding the image, but it adds it as an element so it pushes everything else down.
ByteArrayInputStream inputStream = new ByteArrayInputStream(svgAsBytes);
Image image = SvgConverter.convertToImage(inputStream, pdf);
image.scaleAbsolute(PageSize.A4.getWidth(), PageSize.A4.getHeight());
int totalPages = pdf.getNumberOfPages()+1;
for(int pageNumber = 1; pageNumber < totalPages; pageNumber++ ) {
document.add(image);
}
Hi i have a similar Problem. I am trying to add a SVG image as a table cell background. The problem is that i can not scale the image. Here is my code:
InputStream triangleSteam = this.getClass().getResourceAsStream("/AH-AddressTriangle.svg");
Image triangle = SvgConverter.convertToImage(triangleSteam, pdfDocument);
//triangle.setHeight(UnitValue.createPointValue(127.83f));
//triangle.setWidth(UnitValue.createPointValue(78.63f));
triangle.scaleAbsolute(78.63f, 127.83f);
Cell headerCell_12 = new Cell();
headerCell_12.setBorder(Border.NO_BORDER);
headerCell_12.setPadding(0f);
headerCell_12.setHeight(UnitValue.createPointValue(127.83f));
headerCell_12.setWidth(UnitValue.createPointValue(78.63f));
headerCell_12.setNextRenderer(new ImageBackgroundCellRenderer(headerCell_12, triangle));
headerTable.addCell(headerCell_12);
And here ist the BackgroundCellRenderer I am using:
protected class ImageBackgroundCellRenderer extends CellRenderer {
Image img;
public ImageBackgroundCellRenderer(Cell modelElement, Image img) {
super(modelElement);
this.img = img;
}
#Override
public IRenderer getNextRenderer() {
return new ImageBackgroundCellRenderer((Cell) modelElement, img);
}
#Override
public void draw(DrawContext drawContext) {
try {
img.scaleToFit(getOccupiedAreaBBox().getWidth(), getOccupiedAreaBBox().getHeight());
drawContext.getCanvas().addXObject(img.getXObject(), getOccupiedAreaBBox());
super.draw(drawContext);
} catch(Exception e) {
e.printStackTrace();
}
}
}
The background is added but the image is not scaled (see picture)
Screenshot from Adobe Illustrator
The SVG becomes even bigger that it actually was!
Thank you!
**I'm using the below code to fetch the multiple failure screenshots from the folder to Bugzilla tool, while uploading the pictures in bugzilla, color of the picture is disorted. [enter image description here][1]. Can any one help me to rectify this issue. ? **
try {
BugzillaConnector conn = new BugzillaConnector();
conn.connectTo("bugzilla.com");
LogIn logIn = new LogIn("username", "password");
conn.executeMethod(logIn);
Bug bug = new BugFactory()
.newBug()
.setProduct("SeleniumFramework")
.setComponent("CoreJavaTestNG")
.setVersion("1.0").setPlatform("PC")
.setOperatingSystem("Windows")
.setDescription("Bug posted from Java Source Code")
.setSummary("Bug posted from Java Source Code")
.createBug();
ReportBug report = new ReportBug(bug);
conn.executeMethod(report);
int bugID = report.getID();
System.out.println("Bug posted and its ID is " + bugID);
GetBug get = new GetBug(bugID);
conn.executeMethod(get);
System.out.println(get.getBug().getID());
System.out.println(get.getBug().getSummary());
System.out.println(get.getBug().getProduct());
System.out.println(get.getBug().getComponent());
System.out.println(get.getBug().getVersion());
System.out.println(get.getBug().getPlatform());
System.out.println(get.getBug().getOperatingSystem());
// Passing txtFileFilter to listFiles() method to retrieve only file start with fail files
File[] files = folder.listFiles(txtFileFilter);
int Count = 0;
for (File file : files) {
BufferedImage bImage = ImageIO.read(new File(FilePath + file.getName()));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bImage, "jpg", bos );
byte [] data = bos.toByteArray();
AttachmentFactory attachmentFactory = new AttachmentFactory();
Attachment attachment = attachmentFactory.newAttachment()
. setData(data)
. setMime("image/jpg") //Set the appropriate MIME type for the image format
. setSummary(file.toString()) //Description
. setName(file.toString())//Name of the Screenshot in Bugzilla
. setBugID(bugID)
. createAttachment();
AddAttachment add2 = new AddAttachment(attachment, bugID);
add2.getID();
conn.executeMethod(add2);
Count++;
}
System.out.println(Count + " File Uploded");
}
catch (Exception e) {
e.printStackTrace();
} ```
[1]: https://i.stack.imgur.com/qrIaq.jpg
The pinkish/readish ting your seeing is because the source image contains a alpha channel.
There is a known bug in ImageIO which will include the alpha channel into the output of the JPEG image (or some such thing, you can google it if you're really interested).
The basic solution to your problem is to apply the original image to a BufferedImage using a TYPE_INT_RGB, which will remove the alpha channel, for example see Removing transparency in PNG BufferedImage.
I used the code but am getting blue color background on the image
So, starting with this transparent PNG
And using the below code...
BufferedImage original = ImageIO.read(new File("/Users/shanew/Downloads/transparent.png"));
BufferedImage copy = new BufferedImage(original.getWidth(), original.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = copy.createGraphics();
g2d.setColor(Color.WHITE); // Or what ever fill color you want...
g2d.fillRect(0, 0, copy.getWidth(), copy.getHeight());
g2d.drawImage(original, 0, 0, null);
g2d.dispose();
File dest = new File("Test.jpg");
ImageIO.write(copy, "jpg", dest);
BufferedImage test = ImageIO.read(dest);
JPanel panel = new JPanel();
panel.add(new JLabel(new ImageIcon(original)));
panel.add(new JLabel(new ImageIcon(test)));
JOptionPane.showMessageDialog(null, panel);
I can produce...
If you're still having issues, then you need to do two things:
Update your original question with the code you are using
Provide a sample of the image you are trying to convert
It's not helpful to keep posting code in the comments
So as the title says I am looking for a way to turn SVG to PNG with Apache Batik and then attach this image to PDF file using PDFBox without actually creating the svg and png anywhere.
Currently I have a web form that has SVG image with selectable parts of it.
When the form is submitted I take the "html" part of the svg meaning I keep something like <svg bla bla> <path bla bla/></svg> in a string that Spring then uses to create a ".svg" file in a given folder, then Batik creates a PNG file in the same folder and then PDFBox attaches it to the PDF - this works fine(code below).
//Get the svg data from the Form and Create the svg file
String svg = formData.getSvg();
File svgFile = new File("image.svg");
BufferedWriter writer = new BufferedWriter(new FileWriter(svgFile));
writer.write(svg);
writer.close();
// Send to Batik to turn to PNG
PNGTranscoder pngTranscode = new PNGTranscoder();
File svgFile = new File("image.svg");
InputStream in = new FileInputStream(svgFile);
TranscoderInput tIn = new TranscoderInput(in);
OutputStream os = new FileOutputStream("image.png");
TranscoderOutput tOut = new TranscoderOutput(os)
pngTranscode .transcode(tIn , tOut);
os.flush();
os.close();
//Send to PDFBox to attach to pdf
File pngfile = new File("image.png");
String path = pngfile.getAbsolutePath();
PDImageXObject pdImage = PDImageXObject.createFromFile(path, pdf);
PDPageContentStream contents = new PDPageContentStream(pdf, pdf.getPage(1));
contents.drawImage(pdImage, 0, pdf.getPage(1).getMediaBox().getHeight() - pdImage.getHeight());
contents.close();
As you can see there are a lot of files and stuff (need to tidy it up a bit), but is it possible to do this on the run without the creation and constant fetching of the svg and png files?
Given the suggestion in the comments I opted for using ByteArrayOutputStream, ByteArrayInputStream, BufferedImage and LosslessFactory. Its a bit slower than the saving (if you go through it in debug as seems the BufferedImage goes on a holiday first before creating the image).
The sources I found to use are: How to convert SVG into PNG on-the-fly and Print byte[] to pdf using pdfbox
byte[] streamBytes = IOUtils.toByteArray(new ByteArrayInputStream(formData.getSvg().getBytes()));
PNGTranscoder pngTranscoder = new PNGTranscoder();
ByteArrayOutputStream os = new ByteArrayOutputStream();
pngTranscoder.transcode(new TranscoderInput(new ByteArrayInputStream(streamBytes)), new TranscoderOutput(os));
InputStream is = new ByteArrayInputStream(os.toByteArray());
BufferedImage bim = ImageIO.read(is);
PDImageXObject pdImage = LosslessFactory.createFromImage(pdf, bim);
PDPageContentStream contents = new PDPageContentStream(pdf, pdf.getPage(1));
contents.drawImage(pdImage, 0, pdf.getPage(1).getMediaBox().getHeight() - pdImage.getHeight());
contents.close();
Based on the comments and links provided by D.V.D., I also worked through the problem. I just wanted to post the simple but full example, for anyone wanting to review in the future.
public class App {
private static String OUTPUT_PATH = "D:\\so52875145\\output\\PdfWithPngImage.pdf";
public static void main(String[] args) {
try {
// obtain the SVG source (hardcoded here, but the OP would obtain the String from form data)
byte[] svgByteArray = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"><polygon points=\"200,10 250,190 160,210\" style=\"fill:lime;stroke:purple;stroke-width:1\" /></svg>".getBytes();
System.out.println("Converted svg to byte array...");
// convert SVG into PNG image
PNGTranscoder pngTranscoder = new PNGTranscoder();
ByteArrayOutputStream os = new ByteArrayOutputStream();
pngTranscoder.transcode(new TranscoderInput(new ByteArrayInputStream(svgByteArray)), new TranscoderOutput(os));
System.out.println("Transcoded svg to png...");
// create PDF, and add page to it
PDDocument pdf = new PDDocument();
pdf.addPage(new PDPage());
// generate in-memory PDF image object, using the transcoded ByteArray stream
BufferedImage bufferedImage = ImageIO.read( new ByteArrayInputStream(os.toByteArray()) );
PDImageXObject pdImage = LosslessFactory.createFromImage(pdf, bufferedImage);
System.out.println("Created PDF image object...");
// write the in-memory PDF image object to the PDF page
PDPageContentStream contents = new PDPageContentStream(pdf, pdf.getPage(0));
contents.drawImage(pdImage, 0, 0);
contents.close();
System.out.println("Wrote PDF image object to PDF...");
pdf.save(OUTPUT_PATH);
pdf.close();
System.out.println("Saved PDF to path=[" + OUTPUT_PATH + "]");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
I am trying to create pdf in java using pdfbox 1.8, but problem is I am not able to show CMYK image on pdf so I try to solution on same like below code:
File filePath = new File("C:/Users/msuryawanshi/Documents/10734730431625_C1LA.jpg");
JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(new FileInputStream(filePath));
BufferedImage image = jpegDecoder.decodeAsBufferedImage();
imageUrl = "http://extranet.handgards.com/gs1/10734730431625_C1LA.jpg";
File f = new File("C:/Users/msuryawanshi/Documents/10734730431625_C1LA.jpg");
String url = "http://extranet.handgards.com/gs1/10734730431625_C1LA.jpg";
Iterator readers = ImageIO.getImageReadersByFormatName("JPEG");
ImageReader reader = null;
while (readers.hasNext()) {
reader = (ImageReader) readers.next();
if (reader.canReadRaster()) {
break;
}
}
//Stream the image file (the original CMYK image)
ImageInputStream input = ImageIO.createImageInputStream(f);
reader.setInput(input);
//Read the image raster
Raster raster = reader.readRaster(0, null);
//Create a new RGB image
BufferedImage bi = new BufferedImage(raster.getWidth(), raster.getHeight(),
BufferedImage.TYPE_4BYTE_ABGR);
//Fill the new image with the old raster
bi.getRaster().setRect(raster);
PDXObjectImage ximage = new PDPixelMap(document, bi);
contentStream.drawXObject(ximage, margin + 5, texty, 170, 100);
but image is not meaningful, I have attached output pdf and original image which i want display on my pdf. please help for the same.
PDFBox doesn't support embedding CMYK images at all because java itself can't read such images. You might be able to embed it as an RGB image by using the twelvemonkeys library instead of Java ImageIO to read the JPEG into a BufferedImage. From there, just use PDPixelMap (in 1.8) or LosslessFactory (in 2.0).