itextsharp add text above of chunk image - vb.net

I want to get some text in above of my image. my code like this :
Dim pdfcb As PdfContentByte = Writer.DirectContent
Dim code128 As New Barcode128()
code128.Code = partnumber
code128.Extended = False
code128.CodeType = iTextSharp.text.pdf.Barcode.CODE128
code128.AltText = ""
code128.BarHeight = 13
code128.Size = 6
code128.Baseline = 8
code128.TextAlignment = Element.ALIGN_CENTER
Dim image128 As iTextSharp.text.Image = code128.CreateImageWithBarcode(pdfcb, Nothing, Nothing)
Dim phrase As New Phrase()
phrase.Font.Size = 10
Dim cell As New PdfPCell(phrase)
cell.FixedHeight = 68.69F
cell.HorizontalAlignment = Element.ALIGN_CENTER
cell.VerticalAlignment = Element.ALIGN_MIDDLE
cell.Border = iTextSharp.text.Rectangle.NO_BORDER
phrase.Add(New Chunk(Environment.NewLine + "Companyname"))
phrase.Add(New Chunk(Environment.NewLine + "address"))
phrase.Add(New Chunk(image128, 10, 30))
phrase.Add(New Chunk(Environment.NewLine + partnumber))
phrase.Add(New Chunk(Environment.NewLine + "111"))
tbl.AddCell(cell)
I am always getting my address and company name below of my image.
i want to make that in above of my image
What i can do for that? any help is very appreciable.

You are using PdfPCell in text mode. You shouldn't do that if you want to add an Image. Use PdfPCell in composite mode instead:
Dim cell As New PdfPCell(phrase)
cell.FixedHeight = 68.69F
cell.VerticalAlignment = Element.ALIGN_MIDDLE
cell.AddElement(New Paragraph("CompanyName"))
cell.AddElement(New Paragraph("Address"))
cell.AddElement(image128)
cell.AddElement(New Paragraph(partnumber))
cell.AddElement(New Paragraph("11"))
tbl.AddCell(cell)
Note that I removed the following line:
cell.HorizontalAlignment = Element.ALIGN_CENTER
In composite mode, you need to change the alignment of the elements that you're adding. In this case: you need to change the aligment of the Paragraph objects (that's fairly easy to accomplish). See Alignment, indentation, leading and spacing in cells, How to use multiple fonts in a single cell? and How to right-align text in a PdfPCell?
Your question is also an almost exact duplicate of the question How to put text above a bar code instead of under the bars? which was posted on StackOverflow on January 26, 2016 (little over a month ago).

Related

Create Array of Labels

I'm really hoping to find some way to either create an Array of Label() or to create a Label variable with a constructed name using a string. Unfortunately after searching I'm afraid it won't be possible so I'm looking for alternatives as well.
I have a List of Strings, and I would like to create a Label for each one, inside of a Form using System.Windows.Forms. I am hoping to avoid having one large label holding all of the text, or needing to create a large number of predefined labels, as the number of Strings my list contains will vary from 3 or 4 to 30 or higher.
After some trial and error I have managed to get it not crashing, and the information I am setting to the Label is setting correctly, but becomes nothing outside of the For Loop.
Sub CheckResult(ByRef strList As List(Of String))
Dim LineCount As Integer = strList.Count
Dim Line As String
With CheckForm
.size = New System.Drawing.Size(340, (LineCount * 20) + 40 )
.StartPosition = FormStartPosition.CenterScreen
.MaximizeBox = False
.MinimizeBox = False
.Text = CheckType
End With
Dim CheckTextLabel(0 To LineCount - 1) As Label
Dim i As Integer = 0
For Each Line In strList
Line = strList(i)
CheckTextLabel(i) = New Label()
With CheckTextLabel(i)
.Text = Line
.Size = New System.Drawing.Size(320, 20)
.Location = New System.Drawing.Point(10, 10 + (LineCount * 20))
'.Font = MidFont
End With
CheckForm.Controls.Add(CheckTextLabel(i))
'Location 1
i += 1
Next
'Location 2
...
When I check the value of CheckTextLabel(i).Text at Location 1, I get the expected value.
If I check the value of CheckTextLabel(1) or any other value for i at Location 2, it returns a blank result.
Please let me know if there is a way to do this, and if as I fear there is not, I'll accept alternatives

Create ImageBox in Microsoft Word document and insert image with Visual Basic

I'm working on a project in VB which has to do with document processing in Microsoft Word. I have difficulty on creating an ImageBox with certain size in a the document. Does anybody have an idea on how to do this? Can it even be done? The goal is to create the ImageBox and then insert an image to this box. The image must stretch and get the size of the ImageBox.
What I've done until now is this:
(...)
Dim NewSize As Size
NewSize = New Size(Width, Height)
ResizedImage = New Bitmap(ImageToInsert, NewSize)
(...)
WordDocument.AddPicture(DirectoryAddress & "\ResizedImage." & ImageExtension)
Though, what this code does, is to insert an image with specified size in the Word document. What I want is, the image to stretch and get the size of the ImageBox that will have been created. I hope I was clear enough.
Thanks in advance!
Well, if you were to look at the properties of the table you're creating, you would see that you have not created a table with a fixed height and width. To do that, you could use something like:
NewTable = WordDoc.Tables.Add(para.Range, 1, 1, 0, 0)
NewTable.Cell(1,1).Width(500)
NewTable.Cell(1,1).Height(389)
NewTable.Cell(1, 1).HeightRule(2)
or, in VBA:
Set NewTable = WordDoc.Tables.Add(para.Range, 1, 1, 0, 0)
NewTable.Cell(1,1).Width = 500
NewTable.Cell(1,1).Height = 389
NewTable.Cell(1, 1).HeightRule = 2
Thanks to #CindyMeister and #macropod I managed to create what I needed. So here is the answer:
Dim rng As Word.Range
(...)
rng = para.Range
(...)
Dim img As Image = Image.FromFile(imagePath)
Dim objtable as Word.Table
'In my case I needed a temporary paragraph to be added for my project and later delete it. If you don't need it, just don't declare it.
Dim tempTablePara As Word.Paragraph = WordDoc.Content.Paragraphs.Add() 'Previously declared WordDoc as Word.Document
objtable = WordDoc.Tables.Add(rng, 1, 1)
objtable.Cell(1, 1).Width = img.Width * 0.75 'width is in pixels, convert to points
objtable.Cell(1, 1).Height = img.Height* 0.75 'height is in pixels, convert to points
objtable.Cell(1, 1).HeightRule = Word.WdRowHeightRule.wdRowHeightExactly ' Done so as the cell to get the same size with the picture
Dim objShapes = objtable.Range.InlineShapes
rng = tempTablePara.Range
tempTablePara.Range.Delete()
objShapes.AddPicture(imagePath)
'add cell borders
With objtable.Rows(1).Cells.Borders
.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle
.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle
End With
Extra. What I was looking for, was to insert an image to an already designed frame in a word document. So for me the pre-designed frame was a one cell table. If you just want to add a frame around a picture then the following code should work just fine.
Dim shape
(...)
shape = WordDoc.InlineShapes.AddPicture(imagePath, Type.Missing, Type.Missing, rng)
rng = shape.Range
Dim objshape As Word.InlineShape
objshape = shape
objshape.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingleWavy
objshape.Borders.OutsideColor = Word.WdColor.wdColorBlack
rng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)

Itextsharp fit width and give border

I am designing a table in pdf using itextsharp. I want to ask if anyone knows:
How to give border (like color = silver, 1px, fit to width) to
header text?
How to make table fit to page width (like 100%)?
I am using vb.net
Protected Sub Create_Pdf_Click(sender As Object, e As EventArgs) Handles Create_Pdf.Click
Dim pdfDoc As New Document()
Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(pdfDoc, New FileStream("D://PDF/myfile.pdf", FileMode.Create))
pdfDoc.Open()
pdfDoc.Add(New Paragraph("Here is header text"))
Dim table As New PdfPTable(3)
Dim cell As New PdfPCell(New Phrase("Header spanning 3 columns"))
cell.Colspan = 3
cell.HorizontalAlignment = 1
table.AddCell(cell)
table.AddCell("Col 1 Row 1")
table.AddCell("Col 2 Row 1")
table.AddCell("Col 3 Row 1")
table.AddCell("Col 1 Row 2")
table.AddCell("Col 2 Row 2")
table.AddCell("Col 3 Row 2")
pdfDoc.Add(table)
pdfDoc.Close()
End Sub
When you define a Document like this:
Dim pdfDoc As New Document()
You define a document with pages of size A4 and margins of 36 user units. If you don't want any margins, you need to create your document like this:
Document doc = new Document(PageSize.A4, 0f, 0f, 0f, 0f);
When you create your PdfPTable like this:
Dim table As New PdfPTable(3)
You create a table that takes 80% of the available width. You can change this to 100% by adding this line:
table.WidthPercentage = 100
Or, if you want to specify a specific width, then you can use:
table.TotalWidth = 595f
table.LockedWidth = true
Note that 595 is the width (in user units) of an A4 page.
Borders are defined at the level of a PdfPCell:
PdfPCell cell = new PdfPCell(phrase)
cell.BorderColor = BaseColor.RED
cell.BorderWidth = 3f
cell.Border = Rectangle.BOX
Of course, you can also define each border separately. That is explained here: ITextSharp: Set table cell border color
In your case, you may want to define these properties for the DefaultCell. This way, you don't have to define them over and over again for each separate cell.
It would lead us too far if I would go into more detail (e.g. I could also talk about table events and cell events, for instance to draw dashed borders). Please download the free ebook The Best iText Questions on StackOverflow where you will find the answers to some questions that are even less trivial than yours.

How to align each paragraph specifically by Word Interop?

This is my code:
Dim oWord As Word.Application
Dim oDoc As Word.Document
Dim oTable As Word.Table
Dim oPara1 As Word.Paragraph, oPara2 As Word.Paragraph
Dim oPara3 As Word.Paragraph, oPara4 As Word.Paragraph
Dim oRng As Word.Range
oWord = CreateObject("Word.Application")
oWord.Visible = True
oDoc = oWord.Documents.Add
oPara1 = oDoc.Content.Paragraphs.Add
oPara1.Range.InlineShapes.AddPicture(sNewData.Picture)
oPara1.Format.SpaceAfter = 24
oPara1.Range.InsertParagraphAfter()
oPara2 = oDoc.Content.Paragraphs.Add
oPara2.Range.Text = nTP.Nama
oPara2.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter
oPara2.Range.Font.Bold = True
oPara2.Range.Font.Size = 18
oPara2.Range.Font.Color = Word.WdColor.wdColorBlue
oPara2.Format.SpaceAfter = 6
oPara2.Range.InsertParagraphAfter()
oPara3 = oDoc.Content.Paragraphs.Add
oPara3.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft
oPara3.Range.Text = "Special arrangement for Mr/Mrs. " & customer
oPara3.Range.Font.Color = Word.WdColor.wdColorOliveGreen
oPara3.Format.SpaceAfter = 3
oPara3.Range.InsertParagraphAfter()
The strange thing is the oPara1 is aligned at left, while oPara2 is aligned at center. But the oPara3 is not aligned at left.
The output is that oPara3 is following the previous alignment which is center.
So how could I apply for a specific paragraph its own alignment or style?
I found some discussion about "Style" but I confused.
This C# code aligns the whole Word document successfully:
foreach (Paragraph p in oWord.ActiveDocument.Paragraphs)
{
p.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
}
Your proposal was right, BUT:
When you you modify the property TEXT in the code, the Alignment property restart to Left.
You can try this inserting several times this code to "debug" the status of the Alignment property. One before you set the alignment, one after you modify the alignment, one after you change the "Text" property, then run the program.
Msgbox(oPara3.Range.ParagraphFormat.Alignment)
So the solution is to modify the Alignment just before inserting the Paragraph:
oPara3 = oDoc.Content.Paragraphs.Add
/*oPara3.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft*/
oPara3.Range.Text = "Special arrangement for Mr/Mrs. " & customer
oPara3.Range.Font.Color = Word.WdColor.wdColorOliveGreen
oPara3.Format.SpaceAfter = 3
oPara3.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft
oPara3.Range.InsertParagraphAfter()
AFAIK, Adding a new paragraph is like pressing Enter / Return, so at first format of a new paragraph sets based on Normal Style then after changing any property of current paragraph, it stored as current format that will apply to new paragraphs from now on.
So to change this behavior that makes all new paragraphs to use same format instead of some situation I can suggest to use a method like this - but in C# -:
public static void AddParagraph(ref Document doc, string text,
WdParagraphAlignment align = WdParagraphAlignment.wdAlignParagraphLeft, ...)
// ... means for other format specifications you can do it same
{
var para = doc.Content.Paragraphs.Add();
para.Alignment = align;
para.Range.Text = text;
}
This is what worked for me
Range content = doc.Content;
Paragraph pText = content.Paragraphs.Add();
Text.Range.Text = "sadfsadfsda"
pText.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
I know this is old question, but the solutions mentioned here didn't help me.
So i'll post the solution here for ppl like me in hope it will help them.
The thing you need to do is set the Alignment property AFTER setting the Text property (see the code below).
'p1 is going to be right aligned
var p1 = document.Paragraphs.Add(System.Reflection.Missing.Value)
p1.Range.Font.Name = "Calibri"
p1.Range.Font.Size = 18
p1.Range.Text = "right"
p1.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight
p1.Range.InsertParagraphAfter()
'p2 is going to be center aligned
var p2 = document.Paragraphs.Add(System.Reflection.Missing.Value)
p2.Range.Font.Name = "Calibri"
p2.Range.Font.Size = 16
p2.Range.Text = "center"
p2.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter
p2.Range.InsertParagraphAfter()
'p3 is going to be left aligned
var p3 = document.Paragraphs.Add(System.Reflection.Missing.Value)
p3.Range.Font.Name = "Calibri"
p3.Range.Font.Size = 14;
p3.Range.Text = "left"
p3.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft
p3.Range.InsertParagraphAfter()
This is the way it worked for me.
This is worked for me!
Range content = doc.ActiveDocument.Content;
Paragraph pText = content.Paragraphs.Add();
pText.Range.ParagraphFormat.Alignment =
WdParagraphAlignment.wdAlignParagraphRight;
doc.Selection.TypeText("some text");

How to resize image according to original image ration?

The white background after re-sizing the image using VB.net as shown below. I tried to change some values but failed.
Dim FileToResize As String = Server.MapPath("~/images/" & filename & FileUpload1.FileName)
Using originalBitmap As Bitmap = Bitmap.FromFile(FileToResize, True), newbmp As Bitmap = New Bitmap(200, 200)
Dim WidthVsHeightRatio = CDec(originalBitmap.Width) / CDec(originalBitmap.Height)
Using newg As Graphics = Graphics.FromImage(newbmp)
newg.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
newg.Clear(Color.White)
If WidthVsHeightRatio = 1D Then
newg.DrawImage(originalBitmap, 0, 0, 200, 200)
newg.Save()
ElseIf WidthVsHeightRatio < 1D Then 'Image is taller than wider
newg.DrawImage(originalBitmap, New RectangleF(New PointF((100 - (200 * WidthVsHeightRatio) / 2), 0), New SizeF(200 * WidthVsHeightRatio, 200.0F)))
newg.Save()
Else 'Image is wider than taller
Dim inverse As Double = Math.Pow(WidthVsHeightRatio, -1)
newg.DrawImage(originalBitmap, New RectangleF(New PointF(0, 100 - ((200 * inverse) / 2)), New SizeF(200.0F, 200 * inverse)))
newg.Save()
End If
End Using
newbmp.Save(Server.MapPath("~/images/" & "_th_" & filename & FileUpload1.FileName), System.Drawing.Imaging.ImageFormat.Jpeg)
NewsItem.ImageLink = filename & FileUpload1.FileName
NewsItem.smallimage = "_th_" & filename & FileUpload1.FileName
End Using
I did a bit of research recently for generating Image Thumbnails on the fly for an eCommerce site. I started off doing this myself generating a bitmap and then resizing etc. After problems with image size on disc and quality I looked in to http://imageresizing.net/ and I haven't looked back since. It can generate images from byte(), streams and physicals files all very quickly with one line of code:
ImageBuilder.Current.Build(New MemoryStream(bImage), sImageLocation + sFullFileName, New ResizeSettings("maxwidth=214&maxheight=238"))
I would definitely recommend this component rather than trying to reinvent the wheel...