Itext7 - Crop Image - itext7

Hi How can we resize image in iText 7 .
I am not able to find PDFTemplate in itext 7 now which used to crop image.
.
public Image cropImage(PdfWriter writer, Image image, float leftReduction, float rightReduction, float topReduction, float bottomReduction) throws DocumentException {
float width = image.getScaledWidth();
float height = image.getScaledHeight();
PdfTemplate template = writer.getDirectContent().createTemplate(
width - leftReduction - rightReduction,
height - topReduction - bottomReduction);
template.addImage(image,
width, 0, 0,
height, -leftReduction, -bottomReduction);
return Image.getInstance(template);
}
This is used for itext 5

Suppose that you have this image, measuring 900 x 1200 pixels:
But you only want to show part of this image (e.g. the ping pong balls):
Then you can use this iText 7 code:
PdfDocument pdf = new PdfDocument(new PdfWriter("cropimage.pdf"));
Document document = new Document(pdf);
Image image = new Image(ImageDataFactory.create(imagePath));
image.setFixedPosition(-20, -320);
Rectangle rectangle = new Rectangle(300, 300);
PdfFormXObject template = new PdfFormXObject(rectangle);
Canvas canvas = new Canvas(template, pdf);
canvas.add(image);
Image croppedImage = new Image(template);
document.add(croppedImage);
document.close();
We create an Image instance with the full image, and we set the fixed position in such a way that we chip off 20 pixels from the left, and 320 from the bottom.
We create a rectangle of 300 x 300 user units. This defines the size of the cropped image.
We create a PdfFormXObject using this rectangle. In iText 5 language, a Form XObject used to be named a PdfTemplate.
We create a Canvas object with this template, and we add the image to the canvas.
Finally, we create another Image using the template. The Canvas operation will have added the full image to that template, but it will be cropped to the size of the rectangle.
You can add this croppedImage to the document.

Related

Is that able to change the image size without losing image quality in WPF?

Can I change the image size without losing quality.
I have set the custom size Width and Height to (1100,1100) as below then I get the image blurry.
Bitmap bitmap = new Bitmap("image.jpg");
System.Drawing.Image img = new Bitmap(bitmap,new System.Drawing.Size(1100,1100));
img.Save("output.jpg");

How can I Copy top half of PDF and insert into new PDF

I have an 8.5" x 11" PDF. I'd like to take the top 1/2 of the page, cut it and insert into page 1 of a new PDF. Then, take the bottom 1/2 of the page and insert it into page 2 of the PDF.
I'm essentially trying to split the PDF page in half... All docs I see relate to splitting the individual pages into separate files. I want to essentially copy part of the page and paste it into another doc.
Any help in providing direction using itextsharp? I have used it before and understand the concepts. But, am having a tough time. I'm sure I'll use the rectangle and use the coordinates.
It seems that you are looking to tile a PDF. You're not telling us which version of iText you plan on using. Since you seem to be new at this, I'm assuming that you're using iText 7. In that case, please consult Chapter 6 of the iText 7 Jump-Start tutorial where we tile a PDF with a single page into a PDF with four pages.
Original PDF:
Tiled PDF:
See TheGoldenGateBridge_Tiles for the code:
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfDocument sourcePdf = new PdfDocument(new PdfReader(src));
PdfPage origPage = sourcePdf.getPage(1);
PdfFormXObject pageCopy = origPage.copyAsFormXObject(pdf);
Rectangle orig = origPage.getPageSize();
//Tile size
Rectangle tileSize = PageSize.A4.rotate();
AffineTransform transformationMatrix = AffineTransform.getScaleInstance(
tileSize.getWidth() / orig.getWidth() * 2f,
tileSize.getHeight() / orig.getHeight() * 2f);
//The first tile
PdfPage page = pdf.addNewPage(PageSize.A4.rotate());
PdfCanvas canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, 0, -orig.getHeight() / 2f);
//The second tile
page = pdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, -orig.getWidth() / 2f, -orig.getHeight() / 2f);
//The third tile
page = pdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, 0, 0);
//The fourth tile
page = pdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, -orig.getWidth() / 2f, 0);
// closing the documents
pdf.close();
sourcePdf.close();
Changing this example into code that tiles a PDF with 1 page into a PDF with 2 pages, is a matter of using some simple Math.
If you're using iText 5, then the question was already answered many times before. See for instance:
Tiling with iText, and adding margins
Tile PDF pages vertically with iTextSharp
How to tile a pdf to multiple pages with a border

How to achieve high quality cropped images from canvas?

I am desperately searching for a good cropping tool. There are a bunch out there, for example:
Croppic
Cropit
Jcrop
The most important thing that I am trying to find is a cropping tool, that crops images without making the cropped image low in resolution. You can hack this by using the canvas tag by resizing the image. This way the image itself stays native, only the representation is smaller.
DarkroomJS was also something near the solution, but, unfortunately, the downloaded demo did not work. I'll try to figure out whats wrong. Does someone know some great alternatives, or how to get the cropped images in...let's say "native" resolution?
Thanks in advance!
You are relying on the cropping tool to provide an interface for the users. the problem is that the image returned is sized to the interface and not the original image. Rather than me sifting through the various API's to see if they provide some way of controlling this behaviour (I assume at least some of them would) and because it is such a simple procedure I will show how to crop the image manually.
To use JCrop as an example
Jcrop provides various events for cropstart, cropmove, cropend... You can add a listener to listen to these events and keep a copy of the current cropping interface state
var currentCrop;
jQuery('#target').on('cropstart cropmove cropend',function(e,s,crop){
currentCrop = crop;
}
I don't know where you have set the interface size and I am assuming the events return the crop details at the interface scale
var interfaceSize = { //you will have to work this out
w : ?,
h : ?.
}
Your original image
var myImage = new Image(); // Assume you know how to load
So when the crop button is clicked you can create the new image by scaling the crop details back to the original image size, creating a canvas at the cropped size, drawing the image so that the cropped area is corectly positioned and returning the canvas as is or as a new image.
// image = image to crop
// crop = the current cropping region
// interfaceSize = the size of the full image in the interface
// returns a new cropped image at full res
function myCrop(image,crop,interfaceSize){
var scaleX = image.width / interfaceSize.w; // get x scale
var scaleY = image.height / interfaceSize.h; // get y scale
// get full res crop region. rounding to pixels
var x = Math.round(crop.x * scaleX);
var y = Math.round(crop.y * scaleY);
var w = Math.round(crop.w * scaleX);
var h = Math.round(crop.h * scaleY);
// Assume crop will never pad
// create an drawable image
var croppedImage = document.createElement("canvas");
croppedImage.width = w;
croppedImage.height = h;
var ctx = croppedImage.getContext("2d");
// draw the image offset so the it is correctly cropped
ctx.drawImage(image,-x,-y);
return croppedImage
}
You then only need to call this function when the crop button is clicked
var croppedImage;
myButtonElement.onclick = function(){
if(currentCrop !== undefined){ // ensure that there is a selected crop
croppedImage = myCrop(myImage,currentCrop,interfaceSize);
}
}
You can convert the image to a dataURL for download, and upload via
imageData = croppedImage.toDataURL(mimeType,quality) // quality is optional and only for "image/jpeg" images

Rotate paragraphs or cells some arbitrary number of degrees -- Itext

I have a web site where the users upload photos and create photobooks. Also, they can add text at absolute positions, rotations, and alignments. The text can have new lines.
I've been using the Itext Library to automatize the creation of the Photobooks High Quality Pdfs that are printed latter on.
Adding the user uploaded images to the PDFs was really simple, the problem comes when I try to add the text.
In theory what I would need to do, is to define a paragraph of some defined width and height, set the users text, font, font style, alignment (center, left, right, justify), and finally set the rotation.
For what i've read about Itext, i could create a paragraph set the user properties, and use a ColumnText Object to set the absolute position, width and height. However it's not possibly to set the rotation of anything bigger than single line.
I can't use table cells either, because the rotation method only allow degrees that are multiples of 90.
Is there a way to add a paragraph with some rotation (say 20 degrees) without having to add the text line by line using the ColumnText.showTextAligned() method and all math that involves?
---- Edit: 08-Ago-2013 ----
If it helps anyone, this is the code I used to solve this problem (thanks to Bruno):
//Create the template that will contain the text
PdfContentByte canvas = pdfWriter.getDirectContent();
PdfTemplate textTemplate = canvas.createTemplate(imgWidth, imgHeight); //The width and height of the text to be inserted
ColumnText columnText = new ColumnText(textTemplate);
columnText.setSimpleColumn(0, 0, imgWidth, imgHeight);
columnText.addElement(paragraph);
columnText.go();
//Create de image wraper for the template
Image textImg = Image.getInstance(textTemplate);
//Asign the dimentions of the image, in this case, the text
textImg.setInterpolation(true);
textImg.scaleAbsolute(imgWidth, imgHeight);
textImg.setRotationDegrees((float) -textComp.getRotation()); //Arbitrary number of degress
textImg.setAbsolutePosition(imgXPos, imgYPos);
//Add the text to the pdf
pdfDocument.add(textImg);
Create a PdfTemplate object; just a rectangle.
Draw your ColumnText on this PdfTemplate; don't worry about the rotation, just fill the rectangle with whatever content you want to add to the column.
Wrap the PdfTemplate inside an Image object; this is just for convenience, to avoid the math. This doesn't mean your text will be rasterized.
Now apply a rotation and an absolute position to the Image and add it to your document.
Your problem is now solved ;-)
PS: I'm the author of the iText in Action books.
thanks to both our friends (Bruno & BernalCarlos)
my final code for users that use "RTL" in their projects is here :
// step 1
Document document = new Document();
document.setPageSize(PageSize.A4);
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(destination_file));
CreateBorder event = new CreateBorder();
writer.setPageEvent(event);
// step 3
document.open();
// step 4
int imgWidth=400;
int imgHeight=50;
//Create the template that will contain the text
PdfContentByte canvas = writer.getDirectContent();
PdfTemplate textTemplate = canvas.createTemplate(imgWidth, imgHeight);
//The width and height of the text to be inserted
ColumnText columnText = new ColumnText(textTemplate);
columnText.setSimpleColumn(0, 0, imgWidth, imgHeight);
columnText.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
columnText.addElement(new Paragraph("محاسبه بار غیر متعادل", font_IranSemiBold));
columnText.go();
//Create de image wraper for the template
Image textImg = Image.getInstance(textTemplate);
//Asign the dimentions of the image, in this case, the text
textImg.setInterpolation(true);
textImg.scaleAbsolute(imgWidth, imgHeight);
textImg.setRotationDegrees(90); //Arbitrary number of degress
textImg.setAbsolutePosition(50, 200);
//Add the text to the pdf
document.add(textImg);
// step 5
document.close();

opencv: change image size without effecting content size

I am getting image containing character after applying my image process. All these images (having character as content) have different size. I want to resize all images in same size without effecting it's content size. see below image:
http://techsture.com/img.jpg
I have tried some function to merge my source image with other white image but it needs both source images with same size. I need common size of images for further process.
Please guide me how can I convert my images to common size ??
Thank you
I would make a new image with the destination size, set a ROI in this new image to where you want the source image to show. Then use cvResize.
It should look something like:
int newWidth = 100;
int newHeight = 100;
CvRect rect;
IplImage* source = cvLoadImage("c:/myimage");
IplImage* dest = cvCreateImage(cvSize(newWidth,newHeight),source->depth,source->nChannels);
rect.x = newWidth/2 - source->width/2;
rect.y = newHeight/2 - source->height/2;
rect.width = source->width;
rect.height = source->height;
cvSetImageROI(dest,rect);
cvResize(source,dest);
cvResetImageROI(dest);

Resources