iText header: add logo img on the left side and text on the right side - image

I´m new to iText.
I would like to make a header that will be the same on each page.
The page header will look something like this:
logo.jpg some text
How can I do that?
I have read this link:
http://developers.itextpdf.com/question/how-generate-report-dynamic-header-pdf-using-itextsharp
and I have a problem because I cant add an image to pharse.
Image image = Image.GetInstance(Server.MapPath(mclLogo));
phrase.Add(image);
Throws the Error:
Insertion of illegal Element: 32
Edit: I have tried with paragraph and glue:
Paragraph paragraph = new Paragraph();
paragraph.Add(image);
paragraph.Add(new Chunk(glue));
paragraph.Add("text on the right");
and the output is 2 lines.
somthing link this:
logo.jpg
some text
edit 2:
I have read this:
http://developers.itextpdf.com/content/itext-7-jump-start-tutorial/chapter-1-introducing-basic-building-blocks
espacially the part:
Image fox = new Image(ImageDataFactory.create(FOX));
Image dog = new Image(ImageDataFactory.create(DOG));
Paragraph p = new Paragraph("The quick brown ")
.add(fox)
.add(" jumps over the lazy ")
.add(dog);
document.add(p);
but I use iText5 and I dont find any way how to make a picture and text in the same line.

Try below code, which works with two different Header plot which plotted at right end with image and Left end one with text.
public override void OnStartPage(PdfWriter writer, iTextSharp.text.Document document)
{
PdfPTable HeaderPlot = new PdfPTable(new float[] { 10F });//Header plot 1
PdfPTable HeaderPlot2 = new PdfPTable(new float[] { 10F });//Header plot 2
PdfPCell cell;//cell 1
PdfPCell cell2;// cell 2
HeaderPlot.TotalWidth = 570F; //width for Header plot 1
HeaderPlot2.TotalWidth = 570F;//width for Header plot 2
cell = new PdfPCell();
cell2 = new PdfPCell();
string path = headerpath;
FileInfo f2 = new FileInfo(path);
FileStream fs = new FileStream(f2.FullName,
FileMode.Open, FileAccess.Read);
BinaryReader rdr = new BinaryReader(fs);
byte[] fileData = rdr.ReadBytes((int)fs.Length);
Image image = Image.GetInstance(fileData);
image.ScaleAbsolute(80, 40); //adjusting image size
image.Alignment = Element.ALIGN_CENTER;
cell = new PdfPCell(image)
{
Border = 0,
HorizontalAlignment = Element.ALIGN_TOP,
VerticalAlignment = Element.ALIGN_TOP
};//Header image position
Font font = FontFactory.GetFont("Calibri Light", 8f, Font.NORMAL,
iTextSharp.text.BaseColor.BLACK);//Initializing font
cell2 = new PdfPCell(new Phrase("Text", font))
{
Border = 0,
HorizontalAlignment = Element.ALIGN_LEFT,
VerticalAlignment = Element.ALIGN_TOP
};//Header Text position
HeaderPlot.AddCell(cell);//adding cell 1 to Headerplot 1
HeaderPlot.WriteSelectedRows(0, -1, 480, 835,
writer.DirectContent);//Position of the header on right end, coordinates on right end(480,835)
HeaderPlot2.AddCell(cell2);//adding cell 2 to Headerplot 2
HeaderPlot2.WriteSelectedRows(0, -1, 40, 835,
writer.DirectContent);//Position of the header on left end, coordinates on left end(40,835)
}

Related

spring excel POI Apache set cell value text alignment center

i want to align center in header0 on Cell Value "testing testing"
val style = workbook.createCellStyle()
style.borderTop = 24.toShort() // double lines border
style.borderBottom = 24.toShort() // single line border
val font = workbook.createFont()
font.fontHeightInPoints = 15.toShort()
font.boldweight = XSSFFont.BOLDWEIGHT_BOLD
style.setFont(font)
style.borderRight = 6.toShort()
style.borderLeft = 6.toShort()
var rowNum = 11
var rowNumber = 1
header0.createCell(0).setCellValue("TESTING TESTING")
cell value will be align center

iTextSharp : image in cell doesn't expand

Hi I'm using iTextSharp 535 .
I have a table with 4rows and 3 columns with images added into paragraphs as chunks.
The image size has been resized at 640x480 , the cell with the image has a fixed height.
Dim fra As New Phrase()
Dim imageBytes = ResizeImage(Base64Value)
ImageB = iTextSharp.text.Image.GetInstance(imageBytes)
Dim Pimg As New Paragraph(vbCrLf)
Pimg.Add(New Chunk(ImageB, 0, 0, True))
Pimg.Alignment = Element.ALIGN_CENTER
fra.Add(Pimg)
Dim cell2 = New PdfPCell(fra)
cell2.FixedHeight = 320
table.AddCell(cell2)
But I get a strange result: the image doesn't expand in the next page but it is placed small at the end of it.

Something strange with positioning text with custom font in Itext7

I'm working on a program that creates several pdf docs and puts different text in the same location in them.
Text should be placed in a particular area and if it doesn't fit it in width it should wrap. It also has a custom font and may be differently aligned in that area. It should be Vertically aligned to Top because when the area is laid out for three lines and I has only one, it should appear on the top. Finally, I need to preserve leading on the level of font-size.
It is important to be precise in text positioning (e.g. I need an upper left corner of "H" from "Hello world" to appear definitely at 0, 100).
Now, I'm using
canvas.showTextAligned(paragraph, 0, 300,
TextAlignment.valueOf(alignment),
VerticalAlignment.TOP);
However, when I try to implement it with different fonts it has a various offset from desired y = 300. Moreover, offset differ from font to font. For Helvetica (everywhere 50 fontSize is used) offset is about 13 px, for Oswald about 17 px and for SedgwickAveDisplay it is massive 90 px.
I added borders to paragraph for debugging purpose and things become more strange.
Helvetica:
SedgwickAveDisplay:
The full snippet of my code to create pdf is below:
public byte[] createBadgeInMemory(int i) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfDocument newPdf = new PdfDocument(new PdfWriter(out));
srcPdf.copyPagesTo(1,1,newPdf);
PdfPage page = newPdf.getFirstPage();
PdfCanvas pdfCanvas = new PdfCanvas(page);
Canvas canvas = new Canvas(pdfCanvas, newPdf, pageSize);
File defaultFont = new File("src/main/resources/fonts/Helvetica.otf");
PdfFont font = PdfFontFactory
.createFont(fontPath == null ? defaultFont.getAbsolutePath() : fontPath,
PdfEncodings.IDENTITY_H, true);
String value = "Example word";
Paragraph paragraph = new Paragraph(value);
float textWidth = font.getWidth("Example", 50);
paragraph.setWidth(textWidth);
switch (alignment) {
case("CENTER"):
textWidth /= 2;
break;
case("RIGHT"):
break;
default:
textWidth = 0;
break;
}
paragraph.setFont(font)
.setFontSize(fontSize)
.setFixedLeading(fontSize)
.setFontColor(new DeviceRgb(red, green, blue))
.setMargin(0)
.setPadding(0);
paragraph.setBorderTop(new DashedBorder(Color.BLACK, 0.5f))
.setBorderBottom(new DashedBorder(Color.BLACK, 0.5f))
.setBorderRight(new DashedBorder(Color.BLACK, 0.5f));
paragraph.setHyphenation(new HyphenationConfig(0,
"Example".length()));
canvas.showTextAligned(paragraph,
0 + textWidth,
300,
TextAlignment.valueOf(alignment),
VerticalAlignment.TOP);
newPdf.close();
return out.toByteArray();
}
I also tried variant from here, but for some reason text inside rectangle cuts out at some point (for instance, if I have area width 100px and text snippet I put in that I know occupies exactly 100 px (with the help of font.getWidth(value)), I have my text cut at nearly 80 px).
I also haven't found a way to align text inside a rectangle.
This is the result with Rectangle. A solid border is Rectangle border. As you can see it cuts letter "t" in "Redundant". It also should contain "word" on the second line, but it doesn't.
I copied code from an example.
I need your help. What am I doing wrong or may be there is another way to layout text in particular area with alignment and font?
Thank you in advance.
Update 21.09.17
Also tried variant from this question with SedgwickAveDisplay:
paragraph.setHorizontalAlignment(HorizontalAlignment.LEFT);
paragraph.setVerticalAlignment(VerticalAlignment.TOP);
paragraph.setFixedPosition( 0, 300 - textHeight, "Example".length());
doc.add(paragraph);
The result is the same as on the second screenshot.
This is a font-specific problem. iText guesses information about font glyphs, namely the bboxes incorrectly.
There is a quick and dirty method to adjust this behavior. You can create a custom renderer for text and adjust the calculated positions in it. An example of such a class would be as follows:
class CustomTextRenderer extends TextRenderer {
private CustomTextRenderer(Text text) {
super(text);
}
#Override
public LayoutResult layout(LayoutContext layoutContext) {
LayoutResult result = super.layout(layoutContext);
Rectangle oldBbox = this.occupiedArea.getBBox().clone();
// you can also make the height more than font size or less if needed
this.occupiedArea.setBBox(oldBbox.moveUp(oldBbox.getHeight() - fontSize).setHeight(fontSize));
yLineOffset = fontSize * 0.8f; // here you config the proportion of the ascender
return result;
}
#Override
public IRenderer getNextRenderer() {
return new CustomTextRenderer((Text) modelElement);
}
}
In order that new rendering logic to be applied, you have to use it in the following way:
Text text = new Text(value);
text.setNextRenderer(new CustomTextRenderer(text));
Paragraph paragraph = new Paragraph(text);
Please note that you have to be very careful with this kind of low-level layouting, be aware of you are doing and use this as seldom as possible.
Finally, I created a variant that worked for me.
pdfCanvas.beginText()
.setFontAndSize(font, fontSize)
.setLeading(fontSize)
.moveText(0, 300);
numberOfLines = 0;
sumOfShifts = 0;
float maxWidth = computeStringWidth("Exaxple");
String[] words = value.split("\\s");
StringBuilder line = new StringBuilder();
line.append(words[0]);
float spaceWidth = computeStringWidth(" ") ;
float lineWidth;
for (int index = 1; index < words.length; index++) {
String word = words[index];
float wordWidth = computeStringWidth(word) ;
lineWidth = computeStringWidth(line.toString()) ;
if (lineWidth + spaceWidth + wordWidth <= maxWidth) {
line.append(" ").append(word);
} else {
showTextAligned(alignment, pdfCanvas, line.toString(), lineWidth, maxWidth);
line.delete(0, line.length());
line.append(word);
}
}
if(line.length() != 0) {
lineWidth = computeStringWidth(line.toString()) ;
showTextAligned(alignment, pdfCanvas, line.toString(), lineWidth, maxWidth);
}
pdfCanvas.endText();
As computeStringWidth(String str) I used
Toolkit.getToolkit().getFontLoader().computeStringWidth(String str, Font font);
from import com.sun.javafx.tk.Toolkit with Font from javafx.scene.text.Font. I've chosen it because I use it in other parts of my app.
showTextAligned(...) is my own method that looks this way:
private void showTextAligned(String alignment,
PdfCanvas pdfCanvas,
String line,
float lineWidth,
float maxWidth) {
switch (alignment) {
case "CENTER": {
float shift = (maxWidth - lineWidth) / 2 - sumOfShifts;
pdfCanvas.moveText(shift, 0);
if(numberOfLines == 0) pdfCanvas.showText(line);
else pdfCanvas.newlineShowText(line);
numberOfLines++;
sumOfShifts += shift;
break;
}
case "RIGHT": {
float shift = maxWidth - lineWidth - sumOfShifts;
pdfCanvas.moveText(shift, 0);
if(numberOfLines == 0) pdfCanvas.showText(line);
else pdfCanvas.newlineShowText(line);
numberOfLines++;
sumOfShifts += shift;
break;
}
default:
pdfCanvas.moveText(0, 0);
if(numberOfLines == 0) pdfCanvas.showText(line);
else pdfCanvas.newlineShowText(line);
numberOfLines++;
break;
}
}
In my project, I used my variant, because it gives me an opportunity to work with hyphenation deeper (for instance, I can in future add functionality to avoid putting prepositions as a last word in the line).

How can I get my PdfPTable's border and background color to display (iTextSharp)?

As you can see, I've got a table which sports borders and a background color (Section 1):
...but section 3 lacks these sartorial refinements, and I don't know why.
Here is the pertinent code for section 1 (which displays as it should):
PdfPTable tblHeadings = new PdfPTable(3);
tblHeadings.WidthPercentage = 100;
tblHeadings.SpacingBefore = 10f;
float[] headingRowWidths = new float[] { 550f, 50f, 400f };
tblHeadings.SetWidths(headingRowWidths);
tblHeadings.HorizontalAlignment = Element.ALIGN_LEFT;
Phrase phrasesec1Heading = new Phrase("Section 1: Payment Information", timesRoman9BoldFont);
PdfPCell cellSec1Heading GetCellForBorderedTable(phrasesec1Heading, Element.ALIGN_LEFT, ucscgold);
tblHeadings.AddCell(cellSec1Heading);
. . .
doc.Add(tblHeadings);
...and here for section 3 (which doesn't display as it should):
// Section 3
PdfPTable tblSection3 = new PdfPTable(1);
tblSection3.WidthPercentage = 100;
tblSection3.SpacingBefore = 10f;
//tblSection3.HorizontalAlignment = Element.ALIGN_LEFT;
Chunk sec3PayeeStatus = new Chunk("Section 3: Payee Status", timesRoman9BoldFont);
Chunk requiredFields = new Chunk(" * Required Fields", timesRoman9BoldRedFont);
Paragraph parSection3 = new Paragraph();
parSection3.Add(sec3PayeeStatus);
parSection3.Add(requiredFields);
//Phrase phrasesec1Heading = new Phrase("Section 1: Payment Information", timesRoman9BoldFont);
PdfPCell cellSec3Heading = GetCellForBorderedTable(parSection3, Element.ALIGN_LEFT, ucscgold);
tblSection3.AddCell(cellSec3Heading);
doc.Add(parSection3);
What am I missing or forgetting? The difference in the table creation and setup is in the number of cells/columns, and related declaration (float array) and property (setWidths()). The code adding to the PdfPCell differs in that a Phrase
is used for Section 1 (which displays as I want it to), and a Paragraph is used for section 3 (which doesn't), but I tried that:
// try using a Phrase instead of a Paragraph
Chunk sec3PayeeStatus = new Chunk("Section 3 PayeeStatus",
timesRoman9BoldFont);
Chunk requiredFields = new Chunk(" * Require Fields",
timesRoman9BoldRedFont);
Phrase phraseSection3 = new Phrase();
phraseSection3.Add(sec3PayeeStatus);
phraseSection3.Add(requiredFields);
PdfPCell cellSec3Heading GetCellForBorderedTable(phraseSection3,
Element.ALIGN_LEFT, ucscgold);
tblSection3.AddCell(cellSec3Heading);
doc.Add(phraseSection3);
...but that did no better, in fact was a little worse, because the "SpacingBefore" didn't seem to "take"
Finally (so far), I tried using Phrases instead of Chunks, like so:
Phrase sec3PayeeStatus = new Phrase("Section 3: Payee Status", timesRoman9BoldFont);
Phrase requiredFields = new Phrase(" * Required Fields", timesRoman9BoldRedFont);
Paragraph parSection3 = new Paragraph();
parSection3.Add(sec3PayeeStatus);
parSection3.Add(requiredFields);
PdfPCell cellSec3Heading = GetCellForBorderedTable(parSection3, Element.ALIGN_LEFT, ucscgold);
tblSection3.AddCell(cellSec3Heading);
doc.Add(parSection3);
...but that is no better, worse, or different than the first attempt (at least I get the vertical space back, though, separating sections 2 and 3).
What do I have to do to display the cell borders and background color?
UPDATE
Here's GetCellForBorderedTable():
private static PdfPCell GetCellForBorderedTable(Phrase phrase, int align, BaseColor color)
{
PdfPCell cell = new PdfPCell(phrase);
cell.HorizontalAlignment = align;
cell.PaddingBottom = 2f;
cell.PaddingTop = 0f;
cell.BackgroundColor = color;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
return cell;
}
The problem was (not "visible" to me until I compared the code in a code comparison utility, namely KDiff3) that I was adding the Paragraph, not the table, to the doc:
doc.Add(parSection3);
Now that I've changed that to:
doc.Add(tblSection3);
...it works.

Migradoc setting an image next to text

I want to float an image on the right of some text in a table cell.
cell.AddParagraph("some text");
cell.AddParagraph("next line other text");
Paragraph p = cell.AddParagraph();
p.Format.Alignment = ParagraphAlignment.Right;
p.Format.RightIndent = 12;
Image image = p.AddImage("image.png");
image.ScaleWidth = 0.07;
This code puts the image to the right, but I can't move it up.
p.Format.Linespacing = -10;
image.WrapFormat.DistanceTop = -10;
These settings did not work.
For moving elements up or down SpaceBefore and SpaceAfter can be used.
In this case:
p.Format.SpaceBefore = - 20;

Resources