itextsharp: how do i place an image all the way at the bottom? - vb.net

i have an image that i just want to place all the way at the bottom of the page. how do i do this?

'Set these as needed
Dim DocumentWidth = 1000
Dim DocumentHeight = 1000
Dim ImagePath = "c:\test.jpg"
Dim ImageWidth As Integer
Dim ImageHeight As Integer
Using Img = System.Drawing.Image.FromFile(ImagePath)
ImageWidth = Img.Width
ImageHeight = Img.Height
End Using
'Create the document
Dim D As New Document()
'Set the page size
D.SetPageSize(New iTextSharp.text.Rectangle(0, 0, DocumentWidth, DocumentHeight))
'Zero the margins
D.SetMargins(0, 0, 0, 0)
'Create and open the PDF writer
Dim W = PdfWriter.GetInstance(D, New System.IO.FileStream("C:\test.pdf", IO.FileMode.Create, IO.FileAccess.Write, IO.FileShare.Read))
D.Open()
'Make a new image object
Dim I As New iTextSharp.text.Jpeg(New Uri("file:///" & ImagePath))
'Lower left is (0,0), upper right is (1000,1000)
I.SetAbsolutePosition(DocumentWidth - ImageWidth, 0)
'Add the image
D.Add(I)
D.Close()

place it at the top of the page upside down, and flip the page.
edit:
sorry, i was half kidding. there's an example here of positioning an image using the Image.setAbsolutePosition method. You should be able to calculate the parameters to supply to this function based on the size of the image and the size of the document you're working with.

Related

VB.net crop an image (jpg) like ms paint with no quality loss

Given an jpg image slightly larger than 19" x 23" I need to crop it to exactly 19" x 23" and preserve the original quality using VB.NET.
I can do this in MS paint, If I open a 2851 x 4651 200 DPI jpg and use the Image Properties dialog I can change the width and Height to 3800 x 4600 (exactly 19" x 23" # 200 DPI).
The resultant image is identical to the original in quality and compression but is cropped on the right and bottom by the 51 pixels. The file size is slightly smaller as expected.
When I use the many techniques I have found on SO to crop/resize an image when I save the image it always saves as 96 DPI. I can adjust the width and height to accommodate the 96 DPI so the end result is exactly 19" x 23", however the resulting pixilation is higher than the original, and the files size is considerably smaller, so obvious quality loss.
What I want is to do is (a simple?) crop like MS paint does. Just take a little off the side and bottom, but I cannot seem to save an image with anything other than 96 DPI.
If I can figure out how to the save the cropped file at 200 DPI (or whatever the original image was) I think what I have will work fine.
I am willing to use an external library if that is what it takes.
Here is one example that works in the sense that the resulting image is 19" x 23" and the image is actually scaled preserving the aspect ratio, however the quality is less than the original.
This code is from another SO answer with some minor modifications.
Public Shared Function ResizeImage(SourceImage As Drawing.Image, TargetWidthIn As Decimal, TargetHeightIn As Decimal) As Drawing.Bitmap
'Dim TargetWidth As Integer = TargetWidthIn * SourceImage.HorizontalResolution
'Dim TargetHeight As Integer = TargetHeightIn * SourceImage.VerticalResolution
Dim TargetWidth As Integer = TargetWidthIn * 96
Dim TargetHeight As Integer = TargetHeightIn * 96
Dim bmSource = New Drawing.Bitmap(SourceImage)
Dim bmDest As New Drawing.Bitmap(TargetWidth, TargetHeight, Drawing.Imaging.PixelFormat.Format32bppArgb)
Dim nSourceAspectRatio = bmSource.Width / bmSource.Height
Dim nDestAspectRatio = bmDest.Width / bmDest.Height
Dim NewX = 0
Dim NewY = 0
Dim NewWidth = bmDest.Width
Dim NewHeight = bmDest.Height
If nDestAspectRatio = nSourceAspectRatio Then
'same ratio
ElseIf nDestAspectRatio > nSourceAspectRatio Then
'Source is taller
NewWidth = Convert.ToInt32(Math.Floor(nSourceAspectRatio * NewHeight))
NewX = Convert.ToInt32(Math.Floor((bmDest.Width - NewWidth) / 2))
Else
'Source is wider
NewHeight = Convert.ToInt32(Math.Floor((1 / nSourceAspectRatio) * NewWidth))
NewY = Convert.ToInt32(Math.Floor((bmDest.Height - NewHeight) / 2))
End If
Using grDest = Drawing.Graphics.FromImage(bmDest)
With grDest
.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
'.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
.InterpolationMode = Drawing.Drawing2D.InterpolationMode.NearestNeighbor
.PixelOffsetMode = Drawing.Drawing2D.PixelOffsetMode.HighQuality
.CompositingMode = Drawing.Drawing2D.CompositingMode.SourceCopy
'.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
'.CompositingMode = Drawing.Drawing2D.CompositingMode.SourceOver
.DrawImage(bmSource, NewX, NewY, NewWidth, NewHeight)
End With
End Using
Return bmDest
End Function
I found a solution on SO here
I modifyed my original code above to keep the DPI of the original image:
Dim TargetWidth As Integer = TargetWidthIn * SourceImage.HorizontalResolution
Dim TargetHeight As Integer = TargetHeightIn * SourceImage.VerticalResolution
Then after the call to ResizeImage:
Select Case imageType.ToLower
Case "jpg"
Dim jpgEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Jpeg)
Dim myEncoder As System.Drawing.Imaging.Encoder = System.Drawing.Imaging.Encoder.Quality
Dim myEncoderParams As New EncoderParameters(1)
Dim myEncoderQuality As New EncoderParameter(myEncoder, CType(98L, Int32)) '98%
myEncoderParams.Param(0) = myEncoderQuality
bm.SetResolution(img.HorizontalResolution, img.VerticalResolution)
bm.Save(tempfile, jpgEncoder, myEncoderParams)
Case "png", "gif"
bm.Save(tempfile, System.Drawing.Imaging.ImageFormat.Png)
Case "tiff", "tif"
bm.Save(tempfile, System.Drawing.Imaging.ImageFormat.Tiff)
Case Else
bm.Save(tempfile, System.Drawing.Imaging.ImageFormat.Png)
End Select
bm.Dispose()
I only use jpg now so I don't know if the tiff and png parts work, but it seems using the jpeg encoder allowed me to save the file with 200 DPI and maintain the original quality.
Here is the GetEncoder part that is missing from the other post:
Private Shared Function GetEncoder(f As Drawing.Imaging.ImageFormat) As ImageCodecInfo
Dim myEncoders() As ImageCodecInfo
myEncoders = ImageCodecInfo.GetImageEncoders()
Dim numEncoders As Integer = myEncoders.GetLength(0)
Dim strNumEncoders As String = numEncoders.ToString()
' Get the info. for all encoders in the array.
If numEncoders > 0 Then
Dim myEncoderInfo(numEncoders * 10) As String
For i As Integer = 0 To numEncoders - 1
If myEncoders(i).FilenameExtension.Contains(f.ToString.ToUpper) Then
Return myEncoders(i)
End If
Next
End If
Return Nothing

How to auto align and adjust text in VB.net that getting converted to Image

I was trying with a code that coverts Text to Image using Vb.net and my problem is I need to accept a message from user (Max 160 Characters) by a text box and i need to convert it to a Image. The generated image should be aligned in the middle and the image max resolution should be 800x600.
So the message should be neatly aligned in new lines if needed and perfectly aligned to the middle.
The code I am trying is as follows:
======================================================
Try
Dim Text As String = TextBox3.Text
Dim FontColor As Color = Color.Blue
Dim BackColor As Color = Color.White
Dim FontName As String = "Times New Roman"
Dim FontSize As Integer = 36
Dim Height As Integer = 60
Dim Width As Integer = 200
Dim daten As String
daten = Now.ToString("ddMMyyyyhhmmss")
Dim FileName As String = daten
Dim objBitmap As New Bitmap(Width, Height)
Dim objGraphics As Graphics = Graphics.FromImage(objBitmap)
Dim objColor As Color
objColor = Nothing
Dim objFont As New Font(FontName, FontSize)
'Following PointF object defines where the text will be displayed in the
'specified area of the image
Dim objPoint As New PointF(5.0F, 5.0F)
Dim objBrushForeColor As New SolidBrush(FontColor)
Dim objBrushBackColor As New SolidBrush(BackColor)
objGraphics.FillRectangle(objBrushBackColor, 0, 0, Width, Height)
objGraphics.DrawString(Text, objFont, objBrushForeColor, objPoint)
objBitmap.Save("D:\DNB\" + daten + ".JPG", ImageFormat.Jpeg)
PictureBox1.Image = Image.FromFile("D:\DNB\" + daten + ".JPG")
Catch ex As Exception
End Try
Have you tried the MeasureString function of the Graphics object and it's various overrides? With that you can measure how much space a text in a given size and font needs on the screen. With that knowledge you can calculate the upper left point to use to make the text appear centered.

How Can I re-size an image in VB.Net

I need it so that in my code if something evaluates to true it changes the image location and size.
This is my code so far:
With picValueTwentySix
.Location = New Point(302, 134)
.Size = New System.Drawing.Size(169, 40)
.SizeMode = PictureBoxSizeMode.Zoom
End With
Anybody know why it isn't re-sizing?
Thanks!
As everyone has already mentioned, you need to work the the image. Here is a function I made up for ease of use.
Public Function ResizeImage(ByVal image As Image, ByVal size As Size, Optional ByVal preserveAspectRatio As Boolean = True) As Image
Try
Dim newWidth As Integer
Dim newHeight As Integer
If preserveAspectRatio Then
Dim originalWidth As Integer = image.Width
Dim originalHeight As Integer = image.Height
Dim percentWidth As Single = CSng(size.Width) / CSng(originalWidth)
Dim percentHeight As Single = CSng(size.Height) / CSng(originalHeight)
Dim percent As Single = IIf(percentHeight < percentWidth, percentHeight, percentWidth)
newWidth = CInt(originalWidth * percent)
newHeight = CInt(originalHeight * percent)
Else
newWidth = size.Width
newHeight = size.Height
End If
Dim newImage As Image = New Bitmap(newWidth, newHeight)
Using graphicsHandle As Graphics = Graphics.FromImage(newImage)
graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic
graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight)
End Using
Return newImage
Catch ex As Exception
Return image
End Try
End Function
Basically it creates a new blank graphic to the dimensions you request, then copies the original image to it while scaling it to fit. I think if you step throw it a line at a time you should be pretty self explanatory, but ask if you have questions...
As stated by #Plutonix, changing the Picturebox size will not affect the image size itself, you have to make sure the actual image size is bigger than the size of the picture box, set the size mode of the picturebox to stretchimage, in this case once you resize the picture box the change will reflect. Also refresh the picture box after resizing.

iTextSharp Adding Background Color to Watermark Text

I am adding watermark text to PDFs in a class library I have created. The code I posted below works fine, however the watermark is sometimes difficult to read because it overlays with content on the PDF. How would I go about adding a white background color around the watermark text? I basically would like the watermark text to be surrounded inside a white rectangle the size of the text. Thanks
Public Function AddWatermarkText(ByVal tempDirectory As String) As String
' Just return the full path of the PDF if we don't need to add a watermark.
If Me.Document.RevRank <> 0 OrElse Me.Document.ReleaseDate Is Nothing Then Return Me.FullPath
Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
Dim stamper As iTextSharp.text.pdf.PdfStamper = Nothing
Dim gstate As New iTextSharp.text.pdf.PdfGState()
Dim overContent As iTextSharp.text.pdf.PdfContentByte = Nothing
Dim rect As iTextSharp.text.Rectangle = Nothing
Dim watermarkFont As iTextSharp.text.pdf.BaseFont = Nothing
Dim folderGuid As Guid = Guid.NewGuid()
Dim outputFile As String = tempDirectory & System.IO.Path.DirectorySeparatorChar & folderGuid.ToString() & System.IO.Path.DirectorySeparatorChar _
& Me.Document.Prefix & Me.Document.BaseNumber & Me.Document.Revision & ".pdf"
' Create the temp directory to place the new PDF in.
If Not My.Computer.FileSystem.DirectoryExists(tempDirectory) Then My.Computer.FileSystem.CreateDirectory(tempDirectory)
My.Computer.FileSystem.CreateDirectory(tempDirectory & System.IO.Path.DirectorySeparatorChar & folderGuid.ToString())
reader = New iTextSharp.text.pdf.PdfReader(Me.FullPath)
rect = reader.GetPageSizeWithRotation(1)
stamper = New iTextSharp.text.pdf.PdfStamper(reader, New System.IO.FileStream(outputFile, IO.FileMode.Create))
watermarkFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA_BOLD, _
iTextSharp.text.pdf.BaseFont.CP1252, _
iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED)
gstate.FillOpacity = 0.9F
gstate.StrokeOpacity = 1.0F
' Add the watermark to each page in the document.
For i As Integer = 1 To reader.NumberOfPages()
overContent = stamper.GetOverContent(i)
With overContent
.SaveState()
.SetGState(gstate)
.SetColorFill(iTextSharp.text.BaseColor.BLUE)
.Fill()
.BeginText()
.SetFontAndSize(watermarkFont, 8)
.SetTextMatrix(30, 30)
If Me.Document.RevRank = 0 AndAlso Me.Document.ReleaseDate IsNot Nothing Then
.ShowTextAligned(iTextSharp.text.Element.ALIGN_LEFT, UCase(String.Format("CONTROLLED DOCUMENT – THIS COPY IS THE LATEST REVISION AS OF {0}" _
, Date.Now.ToString("ddMMMyyyy"))), 10, rect.Height - 15, 0)
End If
.Fill()
.EndText()
.RestoreState()
End With
Next
stamper.Close()
reader.Close()
Return outputFile
End Function
I usually like to have code that you can just plop in but unfortunately you're code is a little too domain-specific to provide a direct answer (lots of Me.* that we have to guess at) but I can still get you there with a little code refactoring.
To do what you want to do you have to measure the string that you are drawing and then draw a rectangle to those dimensions. The PDF spec doesn't have a concept of "background color" for text and any implementation that makes it look like it does is really just drawing rectangles for you. (Yes, you can highlight text but that's an Annotation which is different.)
So first I'm going to pull things out into variables so that we can reuse and adjust them easier:
''//Text to measure and draw
Dim myText As String = UCase(String.Format("CONTROLLED DOCUMENT – THIS COPY IS THE LATEST REVISION AS OF {0}", Date.Now.ToString("ddMMMyyyy")))
''//Font size to measure and draw with
Dim TextFontSize As Integer = 8
''//Original X,Y positions that we were drawing the text at
Dim TextX As Single = 10
Dim TextY As Single = rect.Height - 15
Next we need to calculate the width and height. The former is easy but the latter requires us to first get the Ascent and Descent of the text and then calculate the difference.
''//Calculate the width
Dim TextWidth As Single = watermarkFont.GetWidthPoint(myText, TextFontSize)
''//Calculate the ascent and decent
Dim TextAscent As Single = watermarkFont.GetAscentPoint(myText, TextFontSize)
Dim TextDescent As Single = watermarkFont.GetDescentPoint(myText, TextFontSize)
''//The height is the difference between the two
Dim TextHeight As Single = TextAscent - TextDescent
(NOTE: I'm not sure if GetWidthPoint(), GetAscentPoint() and GetDescentPoint() work as desired with multi-line text.)
Then you probably want to have some padding between the box and text:
''//Amount of padding around the text when drawing the box
Dim TextPadding As Single = 2
Lastly, somewhere before you setup and draw the text you want to first draw the rectangle:
''//Set a background color
.SetColorFill(BaseColor.YELLOW)
''//Create a rectangle
.Rectangle(TextX - TextPadding, TextY - TextPadding, TextWidth + (TextPadding * 2), TextHeight + (TextPadding * 2))
''//Fill it
.Fill()

itextsharp: forcing image to take up entire width in vb.net

the following is a generated PDF with a few images. how do i force the image to take up the entire width of the pdf file?
alt text http://img52.imageshack.us/img52/3324/fullscreencapture121420u.png
The ScalePercent method works pretty well for this.
Dim pgSize As New iTextSharp.text.Rectangle(595, 792) //A4 width, Letter height
Dim leftMargin as integer = 20
Dim rightMargin as integer = 20
Dim doc As New iTextSharp.text.Document(pgSize, leftMargin, rightMargin, 48, 24)
//Create PDF and write other stuff.
Dim img As System.Drawing.Image = My.Resources.My_Image
Dim png As System.Drawing.Imaging.ImageFormat = System.Drawing.Imaging.ImageFormat.Png
Dim pic1 As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(img, png)
Dim scaleFactor As Single = (pgSize.Width - leftMargin - rightMargin) / img.Width * 100
pic1.ScalePercent(scaleFactor)
pic1.SetAbsolutePosition(my_X, my_Y)
doc.Add(pic1)