Operation of PDF-iTextSharp-operation image in Asp. Net

Source: Internet
Author: User
Tags image png

 

ITextSharp supports all mainstream image formats, such as jpg, tif, gif, bmp, png, and wmf. use Image in iTextSharp. there are many ways to create images using the GetInstance () method. Perhaps the most common method is to import the file path and file name to this method:

 

String pdfpath = Server. MapPath ("PDFs ");

 

String imagepath = Server. MapPath ("Images ");

 

Document doc = new Document ();

 

Try

 

{

 

Using writer. GetInstance (doc, new FileStream (pdfpath + "/Images.pdf", FileMode. Create ));

 

Doc. Open ();

 

 

 

Doc. Add (new Paragraph ("GIF "));

 

Image gif = Image. GetInstance (imagepath + "/mikesdotnetting.gif ");

 

Doc. Add (gif );

 

}

 

Catch (incluentexception dex)

 

{

 

Response. Write (dex. Message );

 

}

 

Catch (IOException ioex)

 

{

 

Response. Write (ioex. Message );

 

}

 

Catch (Exception ex)

 

{

 

Response. Write (ex. Message );

 

}

 

Finally

 

{

 

Doc. Close ();

 

}

 

 

 

The overload of other constructors that can be used can be a URL or a System. Drawing. Image Object (not iTextSharp. text. Image ).

Note: The System. drawing. image. the FromStream () method uses the namespace alias. As mentioned earlier in the List article, the namespace alias is used to prevent conflicts between two different Image classes :\

 

 

Doc. Add (new Paragraph ("JPG "));

 

String url = "http://www.bkjia.com: 1805/PDF/Images/mikesdotnetting.jpg ";

 

Image jpg = Image. GetInstance (new Uri (url ));

 

Doc. Add (jpg );

 

Doc. Add (new Paragraph ("PNG "));

 

Using (FileStream fs = new FileStream (imagepath + "/mikesdotnetting.png", FileMode. Open ))

 

{

 

Image png = Image. GetInstance (sd. Image. FromStream (fs), ImageFormat. Png );

 

Doc. Add (png );

 

}

 

So far, we cannot identify which image is JPG and PNG, but the resolution of the result image in PDF is not good. By default, the image embedded in PDF is 72 dpi (the number of dots per foot). If the resolution is PDF, it is not enough. Generally, the minimum image resolution required by commercial printers is DPI. to achieve this, you can reduce the size of the 24% DPI image to of the original image. in fact, you want to reduce the original 300 pixel image to 72 pixels: 72/300*100 = 24%. At this time, the size of the image embedded in the pdf file is the same, but the size of the file is much less:

 

 

Doc. Add (new Paragraph ("TIF Scaled to 300 dpi "));

 

Image tif = Image. GetInstance (imagepath + "/mikesdotnetting. tif ");

 

Tif. ScalePercent (24f );

 

Doc. Add (tif );

 

 

 

Now, I have a large image that I want to put as a logo in pdf. The image size is 4.17 feet x 12.36 feet pixels. Therefore, in the case of 72dpi, the image occupies width and height. If you change the image resolution to 1 feet DPI, the image usage will change to 2.97 feet width and height. If you only implement this function, the Code provided above can already achieve this function. However, now I want to place this image in a specific position in the PDF, that is, in the upper right corner. The SetAbsolutePosition () method can be used to achieve this goal, but I still need to calculate the absolute position.

 

The SetAbsolutePosition () method accepts two float-type parameters. The first parameter is the X axis coordinate, which starts from the leftmost part of the document, and the second parameter is the Y axis coordinate, which starts from below the document. The default parameter of A4 paper is 595 pixels wide, 842 pixels high, and the surrounding margins are all 36 pixels.

 

The input coordinate parameter is actually the coordinate in the lower left corner of the image. The distance from the image to the right is 72 pixels (1 feet) in width + 36 pixels in margin (108 pixels in total), so the coordinates of X are 595-108 = 487. for the Y axis, the calculation method is similar to that for the X axis coordinate. the Y axis coordinate is 842-(213.6 + 36) = 592. 4. in fact, I don't need to know the size of all the paper types for math problems, although I need to set the absolute value of the image in the text. Fortunately, I can use the Document. PageSize object to help me remember this number:

 

Image tif = Image. GetInstance (imagepath + "/verticallogo. tif ");

 

Tif. ScalePercent (24f );

 

Tif. SetAbsolutePosition (doc. PageSize. Width-36f-72f,

Doc. PageSize. Height-36f-216.6f );

 

Doc. Add (tif );

Doc. pageSize. width tells me how many pixels the document Width is. I just removed the image Width (72px) and margin (36px) from this Width ). the method for setting Y axis coordinates is the same:

 

 

Put my company Logo in :-)

 

In other application scenarios, for example, you need to provide a container for the images uploaded by users in PDF. I use the default "sunset" example image in WinXp to illustrate how to use the ScaleToFit () method to achieve this effect. the following code shows how to change the size of an image of 800*600 and put it into a 250 pixel long square container without changing its aspect ratio:

 

 

 

Image jpg = Image. GetInstance (imagepath + "/Sunset.jpg ");

 

Jpg. ScaleToFit (250f, 250f );

 

Jpg. Border = Rectangle. BOX;

 

Jpg. BorderColor = Color. YELLOW;

 

Jpg. BorderWidth = 5f;

 

Doc. Add (jpg );

 

Doc. Add (new Paragraph ("Original Width:" + jpg. Width. ToString ()));

 

Doc. Add (new Paragraph ("Original Height" + jpg. Height. ToString ()));

 

Doc. Add (new Paragraph ("Scaled Width:" + jpg. ScaledWidth. ToString ()));

 

Doc. Add (new Paragraph ("Scaled Height" + jpg. ScaledHeight. ToString ()));

 

Float Resolution = jpg. Width/jpg. ScaledWidth * 72f;

 

Doc. Add (new Paragraph ("Resolution:" + Resolution ));

 

In the code above, I added a yellow border of 5 pixels wide to the embedded image. the pre-scaling and post-scaling sizes are shown below, as well as the image resolution. The following is the result:

 

If you use the SetAbsolutePosition () method to achieve the same effect as setting Image. UNDERLYING, unless you want to set a watermark for an Image or something, you can set Image. TEXTWRAP better:

 

 

 

Image jpg = Image. GetInstance (imagepath + "/Sunset.jpg ");

 

Paragraph paragraph = new Paragraph (@ "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. suspendisse blandit turpis. nam in lectus ut dolor consectetuer bibendum. morbi neque ipsum, laoreet id; dignissim et, viverra id, mauris. nulla mauris elit, consectetuer sit amet, accumsan eget, congue ac, libero. vivamus suscipit. nunc dignissim consectetuer lectus. fusce elit nisi; commodo non , Facilisis quis, hendrerit eu, dolor? Suspendisse eleifend nisi ut magna. Phasellus id lectus! Vivamus laoreet enim et dolor. integer arcu mauris, ultricies vel, porta quis, venenatis at, libero. donec nibh est, adipiscing et, ullamcorper vitae, placerat, diam. integer ac turpis vel ligula rutrum auctor! Morbi egestas erat sit amet diam. Ut ipsum? Aliquam non sem. Nulla risus eros, mollis quis, blandit ut; luctus eget, urna. Vestibulum vestibulum dapibus erat. Proin egestas leo a metus? ");

 

Paragraph. Alignment = Element. ALIGN_JUSTIFIED;

 

Jpg. ScaleToFit (250f, 250f );

 

Jpg. Alignment = Image. TEXTWRAP | Image. ALIGN_RIGHT;

 

Jpg. IndentationLeft = 9f;

 

Jpg. SpacingAfter = 9f;

 

Jpg. BorderWidthTop = 36f;

 

Jpg. BorderColorTop = Color. WHITE;

 

Doc. Add (jpg );

 

Doc. Add (paragraph );

 

 

 

In the above example, I add a white border to the image and place it above the text. some lining distance is added to the left and bottom of the image so that it does not keep close to the text. you can set the IndentationLeft and IndentationRight attributes, or use SpacingBefore and SpacingAfter. you may wonder why I set the white border instead of the SpacingBefore attribute. This is a good question. In fact, I have set the SpacingBefore attribute. In this example, I don't know why it doesn't work. If anyone knows, please tell me why. I 'd like to know.

 

Finally, if you need to rotate the image, you can use the Rotation attribute. This property is a float type variable used to indicate the radians of the image rotation. If you are better at school mathematics than I did, the following example will make you more comfortable. if you have a bad math like me and see the following example, you will scream, "Is this a Xiami?" You can read this article about the degree to know Math. PI/2 is actually 90 degrees, or set the RotationDegrees attribute. The degree of this attribute is counter-clockwise. the two methods in the following code achieve the same effect:

 

Jpg. Rotation = (float) Math. PI/2;

 

Jpg. RotationDegrees = 90f;

 

 

------------------------------

Original article: iTextSharp-Working with images Translated by CareySon

 

<Script> </script>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.