Dear Internet Community.
I am trying to build an itextsharp PdfPTable with a row of footer cells with italic text, and I wish to right-align stuff like amount values.
Either I am doing it wrong, or setting alignment AND style is mutually exclusive.
private void AddCellFooterRightAlign(PdfPTable pdfPTable, string text)
{
var phrase = new Phrase(text)
{
Font = FontFactory.GetFont("Arial", Font.DEFAULTSIZE, Font.ITALIC),
};
var pdfPCell = new PdfPCell(phrase)
{
HorizontalAlignment = Element.ALIGN_RIGHT,
};
pdfPTable.AddCell(pdfPCell);
}
This yields a cell with right-aligned, normal-style text.
private void AddCellFooterRightAlign(PdfPTable pdfPTable, string text)
{
var phrase = new Phrase(text)
{
Font = FontFactory.GetFont("Arial", Font.DEFAULTSIZE, Font.ITALIC),
};
var pdfPCell = new PdfPCell()
{
HorizontalAlignment = Element.ALIGN_RIGHT,
};
pdfPCell.AddElement(phrase);
pdfPTable.AddCell(pdfPCell);
}
This yields the opposite: normal-aligned (left), italic-style text.
Notice the subtle difference: By sending the Phrase-object into the Cell constructor, I retain the alignment, but by using AddElement I retain the font style.
Note: I'm stuck with v.5.5.3.0 for the foreseeable future.
Thanks!
-S
The problem is that you are using a Phrase. Use a Paragraph where you can set the font and the alignment.
Related
Hello Everyone,
I have 2 Groups and each group has 3 Label and Text combinations, as you can see from the above Image.
I would like the text field to grab as much as space possible.hence, I have used grab 'true' only for the text field.
These label and text fields are well aligned inside their own group/composite.
But, when these 2 Groups are considered as a whole, the label and text fields are out of alignment.
Is there a way to align these label and text fields across multiple Groups?
is there a way to align these labels and text fields, without declaring each groups having equal column width, and specifying the number of columns label and text fields occupy?
Below is the code I have used for creating the below groups.
private void createFirstGroup(Composite parent) {
Group firstGroup = new Group(parent, SWT.NONE);
firstGroup.setText("first group");
GridDataFactory.fillDefaults().grab(true, false).applyTo(firstGroup);
GridLayoutFactory.fillDefaults().numColumns(2).equalWidth(false).applyTo(firstGroup);
String[] labels = new String[]{"Kwd","Variable","Value"};
for(int index=0;index<labels.length; index++){
Label label = new Label(firstGroup, SWT.NONE);
label.setText(labels[index]);
GridDataFactory.fillDefaults().applyTo(label);
Text textField = new Text(firstGroup, SWT.BORDER);
GridDataFactory.fillDefaults().grab(true, false).applyTo(textField);
}
}
private void createSecondGroup(Composite parent) {
Group secondGroup = new Group(parent, SWT.NONE);
secondGroup.setText("second group");
GridDataFactory.fillDefaults().grab(true, false).applyTo(secondGroup);
GridLayoutFactory.fillDefaults().numColumns(2).equalWidth(false).applyTo(secondGroup);
String[] labels = new String[]{"Count","Upper Comment","Lower Comment"};
for(int index=0;index<labels.length; index++){
Label label = new Label(secondGroup, SWT.NONE);
label.setText(labels[index]);
GridDataFactory.fillDefaults().applyTo(label);
Text textField = new Text(secondGroup, SWT.BORDER);
GridDataFactory.fillDefaults().grab(true, false).applyTo(textField);
}
}
Using iTextSharp version 5.5.8 (same bug existed in 5.5.7), there's an unpleasant bug when you add images to Chapters and Sections - the images and the section headings start out OK but quickly become offset relative to each other.
The PDF generated from the following code starts out correctly, it says "Section 1" and below it is the image. The next section ("Section 2") has a little of the image overlapping the section text, the next section is even worse, etc. I think it's the text that's mal-positioned, not the image.
Is this a known iTextSharp bug?
static Document m_doc = null;
static BaseFont m_helvetica = null;
static Font m_font = null;
static PdfWriter m_writer = null;
static Image m_image = null;
static void Main(string[] args)
{
m_doc = new Document(PageSize.LETTER);
m_helvetica = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
m_font = new Font(m_helvetica, 10.0f);
m_writer = PdfWriter.GetInstance(m_doc, new FileStream("Output.pdf", FileMode.Create));
m_writer.StrictImageSequence = true;
m_doc.Open();
m_doc.Add(new Chunk("Created by iTextSharp version " + new iTextSharp.text.Version().GetVersion, m_font));
Chapter chapter = new Chapter("Chapter 1", 1);
chapter.TriggerNewPage = false;
if (m_image == null)
{
m_image = Image.GetInstance(new Uri("https://pbs.twimg.com/profile_images/2002307628/Captura_de_pantalla_2012-03-17_a_la_s__22.14.48.png"));
m_image.ScaleAbsolute(100, 100);
}
for (int i = 0; i < 5; i++)
{
Section section = chapter.AddSection(18, "Section " + (i + 1));
section.Add(new Chunk(" ", m_font));
section.Add(m_image);
}
m_doc.Add(chapter);
m_doc.Close();
}
From the documentation for the Java version:
A Section is a part of a Document containing other Sections, Paragraphs, List and/or Tables.
Further looking at the Add() method in the C# source we see:
Adds a Paragraph, List, Table or another Section
Basically, instead of a Chunk use a Paragraph. So instead of this
section.Add(new Chunk(" ", m_font));
Use this:
section.Add(new Paragraph(new Chunk(" ", m_font)));
Or even just this:
section.Add(new Paragraph(" ", m_font));
I am trying to generate a pdf on button click. I am having challenge to design the page. If anybody can help on, how to position the text in particular position.
Say I want my address to in the top right corner and heading in the center.
Here is the code I am working on:
private void pdf_btn_Click(object sender, EventArgs e)
{
SaveFileDialog svg = new SaveFileDialog();
svg.ShowDialog();
using (FileStream stream = new FileStream(svg.FileName + ".pdf", FileMode.Create))
{
// Create a Document object
var document = new Document(PageSize.A4, 50, 50, 25, 25);
// Create a new PdfWrite object, writing the output to a MemoryStream
// var output = new MemoryStream();
var writer = PdfWriter.GetInstance(document, stream);
document.Open();
// First, create our fonts... (For more on working w/fonts in iTextSharp, see: http://www.mikesdotnetting.com/Article/81/iTextSharp-Working-with-Fonts
var titleFont = FontFactory.GetFont("Arial", 18, Convert.ToInt32(Font.Bold));
var AddressFont = FontFactory.GetFont("Arial", 7, Convert.ToInt32(Font.Bold));
var boldTableFont = FontFactory.GetFont("Arial", 12, Convert.ToInt32(Font.Bold));
var endingMessageFont = FontFactory.GetFont("Arial", 10, Convert.ToInt32(Font.Italic));
var bodyFont = FontFactory.GetFont("Arial", 12);
// Add the "" title
document.Add(new Paragraph("Certificate of Analysis", titleFont));
// Add Address
var text = document.Add(new Paragraph("Abc Company", AddressFont));
document.Add(new Paragraph("Tel:(xx) xxx-xxxx, (xxx) xxx-xxx", AddressFont));
document.Add(new Paragraph("Fax: (xxx) xxx-xxx, , AddressFont));
document.Close();
stream.Close();
}
}
There are different ways to achieve what you want.
Currently, you are telling iText to do the layout. If you want to center the text "Certificate of Analysis", then you could change the alignment of the Paragraph like this:
Paragraph header = new Paragraph("Certificate of Analysis", titleFont);
header.Alignment = Element.ALIGN_CENTER;
document.Add(header);
If you want the text "Abc Company" to be right-aligned, you can change he alignment like this:
Paragraph company = new Paragraph("Abc Company", AddressFont);
company.Alignment = Element.ALIGN_RIGHT;
document.Add(company);
Of course: when we add company, it will start on a new line under header. Maybe you want the text to be on the same line.
In that case, why not use a PdfPTable?
PdfPTable myTable = new PdfPTable(3);
myTable.WidthPercentage = 100;
PdfPCell mydate = new PdfPCell(new Phrase("April 22, 2015", myfont));
mydate.Border = Rectangle.NO_BORDER;
myTable.AddCell(mydate);
PdfPCell header = new PdfPCell(new Phrase("Certificate of Analysis", titleFont));
header.Border = Rectangle.NO_BORDER;
header.HorizontalAlignment = Element.ALIGN_CENTER;
myTable.AddCell(header);
PdfPCell address = new PdfPCell(new Phrase("Company Address", AddressFont));
address.Border = Rectangle.NO_BORDER;
address.HorizontalAlignment = Element.ALIGN_RIGHT;
myTable.AddCell(address);
doc.Add(myTable);
Now the available width of your page will be divided in three, the date will be aligned to the left, the header will be centered, and the address will be aligned to the right. Obviously, you can add more data to a PdfPCell and more rows to the PdfPTable. This is just a simple proof of concept.
Another option, is to add the text at an absolute position (using coordinates). This can be done by using the ColumnText object. There are plenty of examples on this in The Best iText Questions on StackOverflow
I have underlined "Some text" by
var par = new Paragraph();
par.Add(new Chunk("Some text", CreateFont(12, Font.UNDERLINE)));
document.Add(par);
It is possible underline just "Some text" with dashed line (not the paragraph)?
Thanks
This answer tells you how to do it but unfortunately doesn't provide any code so I've provided it below.
To the best on my knowledge there isn't a direct way to achieve this in iTextSharp by just setting a simple property. Instead, you need to use a PageEvent and manually draw the line yourself.
First you need to subclass PdfPageEventHelper:
private class UnderlineMaker : PdfPageEventHelper {
}
You then want to override the OnGenericTag() method:
public override void OnGenericTag(PdfWriter writer, Document document, iTextSharp.text.Rectangle rect, string text) {
}
The text variable will hold an arbitrary value that you set later on. Here's a full working example with comments:
private class UnderlineMaker : PdfPageEventHelper {
public override void OnGenericTag(PdfWriter writer, Document document, iTextSharp.text.Rectangle rect, string text) {
switch (text) {
case "dashed":
//Grab the canvas underneath the content
var cb = writer.DirectContentUnder;
//Save the current state so that we don't affect future canvas drawings
cb.SaveState();
//Set a line color
cb.SetColorStroke(BaseColor.BLUE);
//Set a dashes
//See this for more details: http://api.itextpdf.com/itext/com/itextpdf/text/pdf/PdfContentByte.html#setLineDash(float)
cb.SetLineDash(3, 2);
//Move the cursor to the left edge with the "pen up"
cb.MoveTo(rect.Left, rect.Bottom);
//Move to cursor to the right edge with the "pen down"
cb.LineTo(rect.Right, rect.Bottom);
//Actually draw the lines (the "pen downs")
cb.Stroke();
//Reset the drawing states to what it was before we started messing with it
cb.RestoreState();
break;
}
//There isn't actually anything here but I always just make it a habit to call my base
base.OnGenericTag(writer, document, rect, text);
}
}
And below is an implementation of it:
//Create a test file on the desktop
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
//Normal iTextSharp boilerplate, nothing special here
using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var doc = new Document()) {
using (var writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
//Bind our helper class
writer.PageEvent = new UnderlineMaker();
//Create a new paragraph
var p = new Paragraph();
//Add a normal chunk
p.Add(new Chunk("This is a "));
//Create another chunk with an arbitrary tag associated with it and add to the paragraph
var c = new Chunk("dashed underline test");
c.SetGenericTag("dashed");
p.Add(c);
//Add the paragraph to the document
doc.Add(p);
doc.Close();
}
}
}
If you wanted to get fancy you could pass a delimited string to SetGenericTag() like dashed-black-2x4 or something and parse that out in the OnGenericTag event.
I am using the iText library to generate text. I am loading the Arial Unicode MS font which does not contain a bold style so iText is simulating the bold. This works fine, but the weight of the bold font appears too heavy compared with text generated using the Java API or even using Microsoft Word.
I tried to get the weight from the FontDescriptor, but the value returned is always 0.0
float weight = font.getBaseFont().getFontDescriptor(BaseFont.FONT_WEIGHT, fontSize);
Is there a way I can change the weight of a simulated bold font?
As an addendum to #Chris' answer: You do not need to construct those Object[]s as there is a Chunk convenience method:
BaseFont arialUnicodeMs = BaseFont.createFont("c:\\Windows\\Fonts\\ARIALUNI.TTF", BaseFont.WINANSI, BaseFont.EMBEDDED);
Font arial12 = new Font(arialUnicodeMs, 12);
Paragraph p = new Paragraph();
for (int i = 1; i < 100; i++)
{
Chunk chunk = new Chunk(String.valueOf(i) + " ", arial12);
chunk.setTextRenderMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE, i/100f, null);
p.add(chunk);
}
document.add(p);
results in
EDIT
Sorry, I just realized after posting this that you're using iText but my answer is for iTextSharp. You should, however, be able to use most of the code below. I've updated the source code link to reference the appropriate Java source.
Bold simulation (faux bold) is done by drawing the text with a stroke. When iText is asked to draw bold text with a non-bold font it defaults to applying a stroke with a width of of the font's size divided by 30. You can see this in the current source code here. The magic part is setting the chunk's text rendering mode to a stroke of your choice:
//.Net code
myChunk.Attributes[Chunk.TEXTRENDERMODE] = new Object[] { PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE, MAGIC_NUMBER_HERE, null };
//Java code
myChunk.attributes.put(Chunk.TEXTRENDERMODE, new Object[]{Integer.valueOf(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE), MAGIC_NUMBER_HERE, null});
Knowing that you can just apply the same logic but using your weight preference. The sample below creates four chunks, the first normal, the second faux-bold, the third ultra-heavy faux-bold and the fourth ultra-lite faux-bold.
//.Net code below but should be fairly easy to convert to Java
//Path to our PDF
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
//Path to our font
var ff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
//Normal document setup, nothing special here
using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var doc = new Document()) {
using (var writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
//Register our font
FontFactory.Register(ff, "Arial Unicode MS");
//Declare a size to use throughout the demo
var size = 20;
//Get a normal and a faux-bold version of the font
var f = FontFactory.GetFont("Arial Unicode MS", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, size, iTextSharp.text.Font.NORMAL);
var fb = FontFactory.GetFont("Arial Unicode MS", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, size, iTextSharp.text.Font.BOLD);
//Create a normal chunk
var cNormal = new Chunk("Hello ", f);
//Create a faux-bold chunk
var cFauxBold = new Chunk("Hello ", fb);
//Create an ultra heavy faux-bold
var cHeavy = new Chunk("Hello ", f);
cHeavy.Attributes = new Dictionary<string, object>();
cHeavy.Attributes[Chunk.TEXTRENDERMODE] = new Object[] { PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE, size / 10f, null };
//Create a lite faux-bold
var cLite = new Chunk("Hello ", f);
cLite.Attributes = new Dictionary<string, object>();
cLite.Attributes[Chunk.TEXTRENDERMODE] = new Object[] { PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE, size / 50f, null };
//Add to document
var p = new Paragraph();
p.Add(cNormal);
p.Add(cFauxBold);
p.Add(cHeavy);
p.Add(cLite);
doc.Add(p);
doc.Close();
}
}
}