I am having header in this format --
"Heading" "Image" "Title"
Below is the code snippet i am using to achieve this -
Paragraph header = section.Headers.Primary.AddParagraph("Heading");
header.Format.Font.Bold = true;
header.AddTab();
Image image = header.AddImage("../../Images/logo.png");
image.Height = Unit.FromMillimeter(6);
header.AddFormattedText("Title", TextFormat.NotBold);
I need to align my "Image" and "Title" in such a way that title is vertically centrally aligned with respect to image's height, how can i achieve this ?
Any pointers/code snippet is much appreciated.
You could use a table to fit all the information in a certain structure:
// create document
Document MigraDokument = new Document();
// create section.
Section section = MigraDokument.AddSection();
section.PageSetup.PageFormat = PageFormat.A4;
// create a table
Table t = section.AddTable();
// size to use for the image and the image cell in the table
int size = 6;
// create 3 columns
Column column_header = t.AddColumn("6cm");
column_header.Format.Alignment = ParagraphAlignment.Center;
Column column_image = t.AddColumn(Unit.FromMillimeter(size));
column_image.Format.Alignment = ParagraphAlignment.Center;
Column column_text = t.AddColumn("4cm");
column_text.Format.Alignment = ParagraphAlignment.Center;
// Add 1 row to fill it with the content
Row r = t.AddRow();
// add you Header
Paragraph header = r.Cells[0].AddParagraph("Heading");
header.Format.Font.Bold = true;
header.AddTab();
// add the image
Image image = r.Cells[1].AddImage("../../logo.png");
image.Height = Unit.FromMillimeter(size);
// Add your Title
r.Cells[2].AddParagraph("Title");
// allign all of them
r.Cells[0].VerticalAlignment = VerticalAlignment.Center;
r.Cells[1].VerticalAlignment = VerticalAlignment.Center;
r.Cells[2].VerticalAlignment = VerticalAlignment.Center;
In my document the result looks the following:
Thanks to #MongZhu for suggesting the table way , posting the code snippet that i am using now just for future reference.
Table table = section.Headers.Primary.AddTable();
table.AddColumn("11cm");
table.AddColumn("2cm");
table.AddColumn("8cm");
Row row = table.AddRow();
row.VerticalAlignment = VerticalAlignment.Center;
Paragraph header = row.Cells[0].AddParagraph("Heading");
header.Format.Font.Bold = true;
Image image = row.Cells[1].AddImage("../../Images/logo.png");
image.Height = Unit.FromMillimeter(6);
row.Cells[2].AddParagraph("Title");
Related
We are creating a PDF, it contains a large table, with headers (bold), sub-headers (non bold), rows and cells.
One of the requirements is to add an already existing PDF (can be multiple pages) inside the cell (under the sub-header). And this is where we are struggling. What we have tried so far:
Converting the PDF to a FormXObject, and adding that into the cell.
FontProvider fontProvider = new FontProvider();
ConverterProperties props = new ConverterProperties();
props.SetFontProvider(fontProvider);
var historyId = text.Replace("=Spectec_template", "");
var pdfTemplate = templateToPdfClient.GetPdf(historyId, "HI").Result;
PdfDocument srcDoc = new PdfDocument(new PdfReader(pdfTemplate.FileStream));
for (int i = 1; i < srcDoc.GetNumberOfPages() + 1; i++)
{
Cell newCell = new Cell(1, columnInfo.ColumnSpan).SetFont(PdfFontFactory.CreateFont(_fontName));
PdfPage origPage = srcDoc.GetPage(i);
Rectangle rect = origPage.GetPageSize();
PdfFormXObject pageCopy = origPage.CopyAsFormXObject(pdf);
Image image = new Image(pageCopy);
image.SetBorder(Border.NO_BORDER);
image.SetMaxWidth(UnitValue.CreatePercentValue(100));
image.SetMaxHeight(UnitValue.CreatePercentValue(50));
Div div = new Div();
div.Add(image.SetMaxWidth(UnitValue.CreatePercentValue(100)));
newCell.Add(div);
newCell = ApplyLayoutsToCell(newCell, cellStyles);
table.AddCell(newCell);
}
But the end result is that we only see 1 page and it's completely overlapping at the end of the page.
When we set image.SetAutoScale(true); the PDF is visible but it's extremely small.
When adding the Image to a Paragraph instead of a DIV the PDF pages display next to each other.
Any ideas, suggestions?
Thank you
Thanks to #mkl and #KJ I figured this out.
I ended up adding each PDF page in a new Cell, and setting the scaling of image to 0.6f.
for (int i = 1; i < srcDoc.GetNumberOfPages() + 1; i++)
{
newCell = new Cell(1, columnInfo.ColumnSpan).SetFont(PdfFontFactory.CreateFont(_fontName));
PdfPage origPage = srcDoc.GetPage(i);
PdfFormXObject pageCopy = origPage.CopyAsFormXObject(pdf);
Image image = new Image(pageCopy);
image.SetBorder(Border.NO_BORDER);
image.Scale(0.6f, 0.6f);
newCell.Add(image);
newCell = ApplyLayoutsToCell(newCell, cellStyles);
table.AddCell(newCell);
}
Hi i'm using SelectPdf for Net Core.
First i generate a method for convert html content to pdf, then i configure my pdf options and finally i add footer in all pages, this work but I can't find any property to center my footer in the document.
public string _htmlStringToBase64(string htmlContent)
{
HtmlToPdf converter = new HtmlToPdf();
converter.Options.PdfPageSize = PdfPageSize.A4;
converter.Options.DisplayFooter = true;
converter.Footer.DisplayOnFirstPage = true;
converter.Footer.DisplayOnOddPages = true;
converter.Footer.DisplayOnEvenPages = true;
converter.Footer.Height = 80;
converter.Options.MarginLeft = 20;
converter.Options.MarginRight = 20;
converter.Options.MarginBottom = 30;
converter.Options.MarginTop = 15;
//this footer options
PdfHtmlSection footerHtml = new PdfHtmlSection(ExternalResources.FooterBase64Img);
footerHtml.AutoFitHeight = HtmlToPdfPageFitMode.ShrinkOnly;
footerHtml.CustomCSS = "text-align: center;"; //I tried that but it doesn't work
converter.Footer.Add(footerHtml);
var docPDF = converter.ConvertHtmlString(htmlContent);
MemoryStream stream = new MemoryStream();
docPDF.Save(stream);
docPDF.Close();
return Convert.ToBase64String(stream.ToArray())
}
As I said, the footer unfolds without problems but I need to center it
The constructor of the PdfHtmlSection class has several overloads, one of them allows the X, Y axes and the url of the image.
You can try assigning a value to the X axis which is the one that aligns horizontally, you can try the following code:
PdfHtmlSection footerHtml = new PdfHtmlSection(100, 0,ExternalResources.FooterBase64Img);
where the 100 value is the position offset from left
the next url show all properties: https://selectpdf.com/docs/Overload_SelectPdf_PdfHtmlSection__ctor.htm
I am using ClosedXML (https://github.com/ClosedXML/ClosedXML) for creating an excel file in my C# MVC Controller. As per the documentation in https://github.com/closedxml/closedxml/wiki/How-can-I-insert-an-image, I have inserted an image in a cell and merged that cell with to cells on the right side.My code is as follows:
For adding image
var imagePath = #"c:\myFolder\image.jpg";
var image = MyWorkSheet.AddPicture(imagePath ) .MoveTo((MyWorkSheet.Cell(3,1).Address)) .Scale(0.2);
image.Width = 50;
image.Height = 50;
For merging cell
MyWorkSheet.Range(MyWorkSheet.Cell(3,1).Address, MyWorkSheet.Cell(3, 3).Address).Merge();
But the image lies on the upper left corner of the cell. I cant find any web source explaining how to center the image in the cell range. Anyone please help me.
You have to move your image with an offset from the cell. To do that, you have to calculate that offset.
Column width is returned in point (not in pixel). You have to convert it to pixel to compare with image pixel width.
So you can do :
int iColumnWidth = (MyWorkSheet.Column(1).Width - 1) * 7 + 12; // To convert column width in pixel unit.
int xOffset = (iColumnWidth - image.Width) / 2;
int yOffset = 0;
image.MoveTo(MyWorkSheet.Cell(3,1), New Point(xOffset, yOffset));
You need to do some manual calculation based on the with respect to image and cell size.
Workbook wb = new Workbook();
Worksheet sheet = wb.Worksheets[0];
sheet.Range["A1"].Text = "Align Picture Within A Cell:";
sheet.Range["A1"].Style.VerticalAlignment = VerticalAlignType.Top;
string picPath = #"C:\Users\Administrator\Desktop\scenery.jpg";
ExcelPicture picture = sheet.Pictures.Add(1, 1, picPath);
sheet.Columns[0].ColumnWidth = 50;
sheet.Rows[0].RowHeight = 150;
picture.LeftColumnOffset =100;
picture.TopRowOffset = 25;
wb.SaveToFile("AlignPicture.xlsx", ExcelVersion.Version2013);
I can not figure out how to vertically align text in table cell. horizontal alignment is ok. I use itextsharp to generate pdf. Alignment should be applied to cells in table kitosKalbosTable. Any help would be appreciated. here's my code:
var table = new PdfPTable(new float[]
{
36, 1, 63
});
table.WidthPercentage = 100.0f;
table.HorizontalAlignment = Element.ALIGN_LEFT;
table.DefaultCell.Border = Rectangle.NO_BORDER;
table.SplitRows = false;
.........
PdfPTable kitosKalbosTable = new PdfPTable(new float[] {10, 30});
kitosKalbosTable.TotalWidth = 40f;
kitosKalbosTable.SplitRows = false;
kitosKalbosTable.AddCell("Kalba", FontType.SmallTimes, vAligment: Element.ALIGN_MIDDLE, hAligment: Element.ALIGN_CENTER);
..........
table.AddCell(kitosKalbosTable);
//method in other file
public static PdfPCell CreateCell(
string text,
FontType? fontType = FontType.RegularTimes,
int? rotation = null,
int? colspan = null,
int? rowspan = null,
int? hAligment = null,
int? vAligment = null,
int? height = null,
int? border = null,
int[] disableBorders = null,
int? paddinLeft = null,
int? paddingRight = null,
bool? splitLate = null)
{
var cell = new PdfPCell();
............
if (vAligment.HasValue)
{
cell.VerticalAlignment = vAligment.Value;
}
return cell;
}
You have a complex example that appears to be using nested tables and extension methods. As Alexis pointed out, the VerticalAlignment is the correct property to use. Below is a full working example of this. I recommend getting rid of your extension method for now and just starting with this example.
//Our test file to output
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
//Standard PDF 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();
//Create our outer table with two columns
var outerTable = new PdfPTable(2);
//Create our inner table with just a single column
var innerTable = new PdfPTable(1);
//Add a middle-align cell to the new table
var innerTableCell = new PdfPCell(new Phrase("Inner"));
innerTableCell.VerticalAlignment = Element.ALIGN_MIDDLE;
innerTable.AddCell(innerTableCell);
//Add the inner table to the outer table
outerTable.AddCell(innerTable);
//Create and add a vertically longer second cell to the outer table
var outerTableCell = new PdfPCell(new Phrase("Hello\nWorld\nHello\nWorld"));
outerTable.AddCell(outerTableCell);
//Add the table to the document
doc.Add(outerTable);
doc.Close();
}
}
}
This code produces this PDF:
Use
cell.VerticalAlignment = Element.ALIGN_MIDDLE; // or ALIGN_TOP or ALIGN_BOTTOM
Also, you can set a default vertical alignment for all cells by setting
kitosKalbosTable.DefaultCell.VerticalAlignment
It seems Element.ALIGN_MIDDLE only works, when the cell height is large i.r.t the text height.
In a PDF, margins for text in cells are large by default, see iText developers
You could append a \n and a space to your string to solve this, but the cell height will become much larger.
For normal text, one way to lift text in a chunk a few pixels is:
myChunk.SetTextRise(value);
Only drawback: when the text is underlined (like a link) it only raises the text ! not the underline..
The following seems to work for underlined text also,
myCell.PaddingBottom = value;
The idea was to put a link in a table cell.. blue font, underlined, vertical centering.
My code now:
iTextSharp.text.Font linksFont =
FontFactory.GetFont(FontFactory.HELVETICA,
10, Font.UNDERLINE, BaseColor.BLUE);
PdfPTable myTable = new PdfPTable(1);
Chunk pt = new Chunk("Go Google Dutch", linksFont);
pt.SetAnchor(new Uri("https://www.google.nl"));
Phrase ph1 = new Phrase(pt);
PdfPCell cellP = new PdfPCell();
cellP.PaddingBottom = linksFont.CalculatedSize/2;
cellP.AddElement(ph1);
myTable.AddCell(cellP);
I am having a table
PdfPTable tblSummary = new PdfPTable(1);
And it does have 2 tables nested within it. How can I make the tblSummary to appear as a whole (the rows must not break to another page) or entire table be shifted to another page if it doesn't fits in the current page.
I have tried SplitLate and SplitRows
And my code is like this
PdfPTable tblSummary = new PdfPTable(1);
PdfPCell csummarycell = new PdfPCell();
PdfPTable tblSummaryFirst = new PdfPTable(3);
.
.
csummarycell.AddElement(tblSummaryFirst);
.
.
tblSummary.AddCell(csummarycell);
tblSummary.SplitLate = true;
tblSummary.SplitRows = false;
like this I add up one more table(s) to the tblSummary while the resulting table height is always less than that of pagesize so there is certainty that the table's content won't be more than the page height.
Any suggestions would be really helping.
Have you tried this:
tblSummary.KeepTogether = true;
PdfPTable tabla = new PdfPTable(2);
float[] anchosTablaTituloDescripcion = new float[] { 4f, 4f };
tabla.SetWidths(anchosTablaTituloDescripcion);
tabla.WidthPercentage = 100;
tabla.KeepTogether = true;