Reputation: 143
I'm trying to center align a block of text, however getting inconsistent results. Here is a rough idea of my code:
baseCanvas.ShowTextAligned("Header 1", 555, 839, TextAlignment.CENTER, 0);
baseCanvas.ShowTextAligned("Test test test ...", 240, 809, TextAlignment.CENTER, 0);
Here is the PDF Output:
However I'm trying to achieve the following:
I've checked the iText documentation, but is there a way to do this without having to create tables and cells?
Upvotes: 1
Views: 16875
Reputation: 1
Div div2 = new Div();
div2.setPaddingLeft(35);
div2.setPaddingRight(35);
div2.setPaddingBottom(5);
div2.add(new Paragraph().add(new Paragraph("Hola Mundo")
.setFontSize(12)
.setTextAlignment(TextAlignment.JUSTIFIED)
.setPaddingLeft(10)
)
.setPaddingBottom(4));
document.add(div2);
Upvotes: 0
Reputation: 507
I do it like this. Where the document is created, get the width of the document.
var document = new Document(pdfDoc);
var pageSize = pdfDoc.GetDefaultPageSize();
var width = pageSize.GetWidth() - document.GetLeftMargin() - document.GetRightMargin();
Then create the paragraph with this function.
private Paragraph CenteredParagraph(Text text, float width)
{
var tabStops = new List<TabStop> { new TabStop(width / 2, TabAlignment.CENTER) };
var output = new Paragraph().AddTabStops(tabStops);
output.Add(new Tab())
.Add(text);
return output;
}
After that just add the paragraph to the document.
document.Add(CenteredParagraph("All the text to add that is centered.");
Upvotes: 0
Reputation: 77528
When you do:
baseCanvas.ShowTextAligned("Some text", x, y, TextAlignment.CENTER, 0);
Then you want the coordinate (x, y)
to coincide with the middle of the text "some text"
.
In your code snippet, you are centering some text around the coordinate (555, 839)
and some text around the coordinate (40, 809)
which explains the difference.
Since you are using iText 7, why don't you take advantage of the fact that you can now easily position Paragraph
objects at absolute positions? The iText 7 jump-start tutorial for .NET already introduces some of the basic building blocks, but the Building blocks tutorial goes into more depth.
Take a look at the first example of chapter 2 and adapt it like this:
PdfPage page = pdf.AddNewPage();
PdfCanvas pdfCanvas = new PdfCanvas(page);
Rectangle rectangle = new Rectangle(36, 650, 100, 100);
Canvas canvas = new Canvas(pdfCanvas, pdf, rectangle);
PdfFont font = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
PdfFont bold = PdfFontFactory.createFont(FontConstants.TIMES_BOLD);
Text title =
new Text("The Strange Case of Dr. Jekyll and Mr. Hyde").SetFont(bold);
Text author = new Text("Robert Louis Stevenson").SetFont(font);
Paragraph p = new Paragraph().Add(title).Add(" by ").Add(author);
p.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);
canvas.Add(p);
canvas.Close();
This should add the text inside the rectangle (36, 650, 100, 100)
and center all content.
Upvotes: 7