ABCPDF Calculation of header size and position. - c#

The problem is a header file, which I have to include on each page of the pdf file generated by abcpdf.
The header file contains more than one image file and several lines of text, which varies from case to case.
The problem is that I do not know how to calculate the size of the header. I need to have its size to allocate the rectangle positions to put the rest of html file on each page together with header. I am using C#.

First off you need to create your document with enough space at the top to allow a header to be added. The settings below are for a normal A4 document with a header of about 1/5 of the page. Remember the coordinates on a PDF are from the bottom right not the top left..
//Setting to create the document using ABCPdf 8
var theDoc = new Doc();
theDoc.MediaBox.String = "A4";
theDoc.HtmlOptions.PageCacheEnabled = false;
theDoc.HtmlOptions.ImageQuality = 101;
theDoc.Rect.Width = 719;
theDoc.Rect.Height = 590;
theDoc.Rect.Position(2, 70);
theDoc.HtmlOptions.Engine = EngineType.Gecko;
The code below out puts a header across each page on the document, with a header image then a colored box under the image with some custom text in.
The header image in this case is 1710 x 381 to keep the resolution of the image as high as possible to stop it looking fuzzy when printed.
private static Doc AddHeader(Doc theDoc)
{
int theCount = theDoc.PageCount;
int i = 0;
//Image header
for (i = 1; i <= theCount; i++)
{
theDoc.Rect.Width = 590;
theDoc.Rect.Height = 140;
theDoc.Rect.Position(0, 706);
theDoc.PageNumber = i;
string imagefilePath = HttpContext.Current.Server.MapPath("/images/pdf/pdf-header.png");
Bitmap myBmp = (Bitmap)Bitmap.FromFile(imagefilePath);
theDoc.AddImage(myBmp);
}
//Blue header box
for (i = 2; i <= theCount; i++)
{
theDoc.Rect.String = "20 15 590 50";
theDoc.Rect.Position(13, 672);
System.Drawing.Color c = System.Drawing.ColorTranslator.FromHtml("#468DCB");
theDoc.Color.Color = c;
theDoc.PageNumber = i;
theDoc.FillRect();
}
//Blue header text
for (i = 2; i <= theCount; i++)
{
theDoc.Rect.String = "20 15 586 50";
theDoc.Rect.Position(25, 660);
System.Drawing.Color cText = System.Drawing.ColorTranslator.FromHtml("#ffffff");
theDoc.Color.Color = cText;
string theFont = "Century Gothic";
theDoc.Font = theDoc.AddFont(theFont);
theDoc.FontSize = 14;
theDoc.PageNumber = i;
theDoc.AddText("Your Text Here");
}
return theDoc;
}

Related

iTextSharp not working in loop

I have 2 pieces of code. The first one is working, second one is inside a loop and it doesn't show the value.
Anyone have any idea? Could it be looping is too fast for memorystream to read?
I am writing everything to a memorystream and response to download the file.
If I do it one by one as below, everything works fine.
var phraseinvoice = new Phrase();
phraseinvoice.Add(new Chunk("Invoice to:", FontFactory.GetFont(FontFactory.TIMES, 12)));
Invoicetable.AddCell(phraseinvoice);
phraseinvoice = new Phrase();
phraseinvoice.Add(new Chunk("BCD Meetings & Events Asia Pacific", FontFactory.GetFont(FontFactory.TIMES_BOLD, 12)));
PdfPCell inheader = new PdfPCell(phraseinvoice);
inheader.PaddingBottom = 4;
inheader.Border = Rectangle.NO_BORDER;
inheader.FixedHeight=20f;
Invoicetable.AddCell(inheader);
If I put them inside a array and read from a for loop the PDF will not show any text.
string[] tbText = {" ","Pte.Ltd"," ", "20 Anson Road, #06-01"," ", "Twenty Anson 079912","",
"Singapore"," "," ","Tel", "1234567", "Fax","123"," "," ","Delivery to:", "BCD Meetings & Events Asia Pacific"," ",
"Pte,Ltd"," ","20 Anson Road, #06-01"," ", "Twenty Anson 079912"," ","Singapore"};
Invoicetable.AddCell(inheader);
for (int i = 0; i < 25; i++)
{
var inputstring = tbText[i];
phraseinvoice = new Phrase();
phraseinvoice.Add(new Chunk(inputstring, FontFactory.GetFont(FontFactory.TIMES_BOLD, 12)));
PdfPCell cellbox = new PdfPCell(phraseinvoice);
cellbox = new PdfPCell(phraseinvoice);
cellbox.Border = Rectangle.NO_BORDER;
cellbox.Padding= -4;
Invoicetable.AddCell(cellbox);
}
You can see the differences between first image after -4 padding and second image without padding
You are creating a Phrase with text in a 12pt font, but you are limiting the height of the cell to 10pt. That explains why nothing is shown.
Change your code like this:
for (int i = 0; i < 25; i++)
{
var inputstring = tbText[i];
phraseinvoice = new Phrase(inputstring,
FontFactory.GetFont(FontFactory.TIMES_BOLD, 12)));
PdfPCell cellbox = new PdfPCell(phraseinvoice);
cellbox.Border = Rectangle.NO_BORDER;
cellbox.FixedHeight = 20f;
Invoicetable.AddCell(cellbox);
}
20 user units should be sufficient to show text in a 12pt font.
Update:
Another option would be to reduce the font size, for instance:
for (int i = 0; i < 25; i++)
{
var inputstring = tbText[i];
phraseinvoice = new Phrase(inputstring,
FontFactory.GetFont(FontFactory.TIMES_BOLD, 8)));
PdfPCell cellbox = new PdfPCell(phraseinvoice);
cellbox.Border = Rectangle.NO_BORDER;
cellbox.FixedHeight = 15f;
Invoicetable.AddCell(cellbox);
}
But there's more: the height needed by a Phrase in a PdfPCell depends on:
The font size,
The leading,
The ascender and descender of the font.
For instance:
for (int i = 0; i < 25; i++)
{
var inputstring = tbText[i];
phraseinvoice = new Phrase(inputstring,
FontFactory.GetFont(FontFactory.TIMES_BOLD, 12)));
PdfPCell cellbox = new PdfPCell(phraseinvoice);
cellbox.Leading = 14;
cellbox.UseAscender = true;
cellbox.UseDescender = true;
cellbox.Border = Rectangle.NO_BORDER;
cellbox.FixedHeight = 18f;
Invoicetable.AddCell(cellbox);
}
Note how we reduced the Leading from the default (1.5 times the font size) to 14, and how we told the cellBox to take the ascender and descender into account.
Looks like you are trying to add a string as a pdfpcell
var inputstring = tbText[i];
Invoicetable.AddCell(inputstring);
tbText is a string array

EPPLUS AutoFit cells

how can i set autosize on my cells, based on the max length of one input.
using (rng = workSheet.Cells["A1:G1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
rng.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue);
rng.Style.Font.Color.SetColor(Color.White);
}
using (ExcelRange col = workSheet.Cells[2, 6, 7, 7])
{
col.Style.Numberformat.Format = "yyyy-mm-dd HH:mm";
col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}
for (int i = 1; i <= a; i++)
{
workSheet.Cells["A1"].Value = "RU_ID";
workSheet.Cells["B1"].Value = "COR_REQ_ID";
workSheet.Cells["C1"].Value = "RU_NAME";
workSheet.Cells["D1"].Value = "PARENT_RU_NAME";
workSheet.Cells["E1"].Value = "ADJUSTMENT_STATE";
workSheet.Cells["F1"].Value = "COR_START";
workSheet.Cells["G1"].Value = "COR_END";
}
...
rng.AutoFitColumns();
string path = #"D:\excel\test.xlsx";
Stream stream = File.Create(path);
excel.SaveAs(stream);
stream.Close();
byte[] data = File.ReadAllBytes(path);
}
The only thing that AutoFitColumn is doing is to bring the cell to the size of the header, as if i have the header as "STH" and the inputs as "Something good", "something to increase cell size" than AutoFitColumn will set the size based on "STH" not "something to increase cell size".
Thanks in advance for the help.
Look at your lines:
using (rng = workSheet.Cells["A1:G1"])
...
rng.AutoFitColumns();
Notice you are call AutoFitColumns on the range of of your headers A1:G1 so EPPlus is using only those cells to determine the width of the columns.
Just do this instead:
workSheet.Cells.AutoFitColumns();
since Cells in Epplus only contain cells with actual values so there is no real concern over efficiency.

Table in Word document with n columns to fit as per page size and allow truncated columns to break across page using Aspose.words for .Net

I'm generating a word document using Aspose.Words(Evaluation mode) for .Net in which I'm building a table as following
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Table table = builder.StartTable();
for (int i = 0; i < 5; i++)
{
for(int j = 0; j < 20; j++)
{
builder.InsertCell();
builder.Write("Column : "+ j.toString());
}
builder.EndRow();
}
builder.EndTable();
doc.Save(ms, Aspose.Words.Saving.SaveOptions.CreateSaveOptions(SaveFormat.Doc));
FileStream file = new FileStream(#"c:\NewDoc.doc", FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();
Now this code gives following word file with invisible columns, it should give 20 columns
.
Is there any way to break invisible columns to next page?
Rows can go to next page, not columns, it is the behavior of Microsoft Word. You can change the design and formatting of the document to make all columns visible. Below are few pointers.
Reduce the page margins (left and right)
Make the cells width fixed. This way, the text inside each cell will break downwards, if more characters found.
Change orientation to landscape, you will have a wider page.
Check the related articles and code sample on Aspose.Words documentation website.
Try the updated code sample below:
string dst = dataDir + "table.doc";
Aspose.Words.Document doc = new Aspose.Words.Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Set margins
doc.FirstSection.PageSetup.LeftMargin = 10;
//doc.FirstSection.PageSetup.TopMargin = 0;
doc.FirstSection.PageSetup.RightMargin = 10;
//doc.FirstSection.PageSetup.BottomMargin = 0;
// Set oriantation
doc.FirstSection.PageSetup.Orientation = Aspose.Words.Orientation.Landscape;
Aspose.Words.Tables.Table table = builder.StartTable();
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 20; j++)
{
builder.InsertCell();
// Fixed width
builder.CellFormat.Width = ConvertUtil.InchToPoint(0.5);
builder.Write("Column : " + j);
}
builder.EndRow();
}
builder.EndTable();
// Set table auto fit behavior to fixed width columns
table.AutoFit(AutoFitBehavior.FixedColumnWidths);
doc.Save(dst, Aspose.Words.Saving.SaveOptions.CreateSaveOptions(Aspose.Words.SaveFormat.Doc));
I work with Aspose as a Developer Evangelist.

Passing a List as a parameter to a Matlab function from C# project

I'm trying to run The Fast Compressive Tracking Algorithm from my C# project. What I want is that, (in C#)to pass the images after converting them into gray scale images to the Matlab function
Runtracker
instead of having the images in the Matlab code as I'm going to apply some operations to specify the index of the array that containing the images to start tracking from.
But when I pass the list of the grayscale images, I got an error says
" The best overload method match for 'trackerNative.FCT.Runtracker(int)' has some invalid arguments."
Can you help me solve this? to pass List of images in C# to a matlab function.
C# Code
//to convert to graScale
public double[,] to_gray(Bitmap img)
{
int w = img.Width;
int h = img.Height;
double[,] grayImage = new double[w, h];
for (int i = 0; i < w; i++)
{
for (int x = 0; x < h; x++)
{
Color oc = img.GetPixel(i, x);
grayImage[i, x] = (double)(oc.R + oc.G + oc.B) / 3;
}
}
return grayImage;
}
//to get the files from specified folder
public static String[] GetFilesFrom(String searchFolder, String[] filters, bool isRecursive)
{
List<String> filesFound = new List<String>();
var searchOption = isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
foreach (var filter in filters)
{
filesFound.AddRange(Directory.GetFiles(searchFolder, String.Format("*.{0}", filter), searchOption));
}
return filesFound.ToArray();
}
//Button to run the matlab function 'Runtracker'
private void button1_Click(object sender, EventArgs e)
{
FCT obj = new FCT(); //FCT is a matlab class
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string file_path = openFileDialog1.FileName;
var filters = new String[] { "png" };
var files = GetFilesFrom(file_path, filters, false);
List< double[,] > imgArr = new List< double[,] >();
for (int i = 0; i < files.Length; i++)
{
Bitmap image = new Bitmap(files[i]);
double[,] grayScale_image = to_gray(image);
imgArr[i] = grayScale_image;
}
object m = obj.Runtracker(imgArr); //the error occured
//Bitmap output = m as Bitmap;
}
}
Matlab Code
function Runtracker(input_imgArr)
clc;clear all;close all;
rand('state',0);
%%
[initstate] = initCt(1);% position of the detected face in the 1st frame
num = length(input_imgArr);% number of frames
%%
x = initstate(1);% x axis at the Top left corner
y = initstate(2);
w = initstate(3);% width of the rectangle
h = initstate(4);% height of the rectangle
%---------------------------
img = imread(input_imgArr(1));
img = double(img);
%%
trparams.init_negnumtrain = 50;%number of trained negative samples
trparams.init_postrainrad = 4;%radical scope of positive samples
trparams.initstate = initstate;% object position [x y width height]
trparams.srchwinsz = 25;% size of search window
%-------------------------
%% Classifier parameters
clfparams.width = trparams.initstate(3);
clfparams.height= trparams.initstate(4);
% feature parameters
% number of rectangle from 2 to 4.
ftrparams.minNumRect =2;
ftrparams.maxNumRect =4;
M = 100;% number of all weaker classifiers, i.e,feature pool
%-------------------------
posx.mu = zeros(M,1);% mean of positive features
negx.mu = zeros(M,1);
posx.sig= ones(M,1);% variance of positive features
negx.sig= ones(M,1);
lRate = 0.85;% Learning rate parameter
%% Compute feature template
[ftr.px,ftr.py,ftr.pw,ftr.ph,ftr.pwt] = HaarFtr(clfparams,ftrparams,M);
%% Compute sample templates
posx.sampleImage = sampleImgDet(img,initstate,trparams.init_postrainrad,1);
negx.sampleImage = sampleImg(img,initstate,1.5*trparams.srchwinsz,4+trparams.init_postrainrad,trpar ams.init_negnumtrain);
%% Feature extraction
iH = integral(img);%Compute integral image
posx.feature = getFtrVal(iH,posx.sampleImage,ftr);
negx.feature = getFtrVal(iH,negx.sampleImage,ftr);
[posx.mu,posx.sig,negx.mu,negx.sig] =
classiferUpdate(posx,negx,posx.mu,posx.sig,negx.mu,negx.sig,lRate);%
update distribution parameters
%% Begin tracking
for i = 2:num
img = imread(input_imgArr(i));
imgSr = img;% imgSr is used for showing tracking results.
img = double(img);
iH = integral(img);%Compute integral image
%% Coarse detection
step = 4; % coarse search step
detectx.sampleImage =
sampleImgDet(img,initstate,trparams.srchwinsz,step);
detectx.feature = getFtrVal(iH,detectx.sampleImage,ftr);
r = ratioClassifier(posx,negx,detectx.feature);% compute the classifier for all samples
clf = sum(r);% linearly combine the ratio classifiers in r to the final classifier
[c,index] = max(clf);
x = detectx.sampleImage.sx(index);
y = detectx.sampleImage.sy(index);
w = detectx.sampleImage.sw(index);
h = detectx.sampleImage.sh(index);
initstate = [x y w h];
%% Fine detection
step = 1;
detectx.sampleImage = sampleImgDet(img,initstate,10,step);
detectx.feature = getFtrVal(iH,detectx.sampleImage,ftr);
r = ratioClassifier(posx,negx,detectx.feature);% compute the classifier for all samples
clf = sum(r);% linearly combine the ratio classifiers in r to the final classifier
[c,index] = max(clf);
x = detectx.sampleImage.sx(index);
y = detectx.sampleImage.sy(index);
w = detectx.sampleImage.sw(index);
h = detectx.sampleImage.sh(index);
initstate = [x y w h];
%% Show the tracking results
imshow(uint8(imgSr));
rectangle('Position',initstate,'LineWidth',4,'EdgeColor','r');
hold on;
text(5, 18, strcat('#',num2str(i)), 'Color','y', 'FontWeight','bold', 'FontSize',20);
set(gca,'position',[0 0 1 1]);
pause(0.00001);
hold off;
%% Extract samples
posx.sampleImage = sampleImgDet(img,initstate,trparams.init_postrainrad,1);
negx.sampleImage =
sampleImg(img,initstate,1.5*trparams.srchwinsz,4+trparams.init_postrainrad,trparams.init_negnumtrain);
%% Update all the features
posx.feature = getFtrVal(iH,posx.sampleImage,ftr);
negx.feature = getFtrVal(iH,negx.sampleImage,ftr);
[posx.mu,posx.sig,negx.mu,negx.sig] = classiferUpdate(posx,negx,posx.mu,posx.sig,negx.mu,negx.sig,lRate);% update distribution parameters
end
end
This is because the Runtracker expects an argument of type int as per the error and you are passing an argument of type int[] i.e an integer array.
The passed parameter and the expected parameter should match in order to execute the method successfully.
Hope this helps.

Cannot get SpacingAfter to work on image with iTextSharp

Hi I would like to add some extra space after a image in my iTextSharp generated pdf document. But for some reason whatever I try to do it will not prevent my text from wrapping
Example image
As you can see the "to read everyth..." does not indent like the rest
This is the codesnip that should do this:
var brevityBox = iTextSharp.text.Image.GetInstance("http://" + domain + "/ImageGen.ashx?Text=" + brevityScore + "&FontSize=120&&FontStyle=Bold&Font=Calibri&Align=Center&image=/media/images/PDF/BrevityBox.jpg");
brevityBox.ScaleToFit(80f, 220f);
brevityBox.Alignment = Image.TEXTWRAP;
brevityBox.SpacingAfter = 460f;
doc.Add(brevityBox);
Chunk c3 = new Chunk(brevityText, FontFactory.GetFont("Verdana", 12, Font.NORMAL)); ;
Paragraph p3 = new Paragraph();
p3.IndentationLeft = 20;
p3.IndentationRight = 20;
p3.Alignment = Element.ALIGN_LEFT;
p3.Add(c3);
doc.Add(p3);
Just to prove the point the SpacingAfter is 460 points.
IndentationRight
works fine
Any ideas?
I believe that iTextSharp is not even using the SpacingAfter property. I modified the method
iTextSharp.text.pdf.PdfDocument.Add(iTextSharp.text.Image image){}
to this:
if (imageEnd < 0 || imageEnd < currentHeight + image.ScaledHeight + diff + image.SpacingAfter)
{
imageEnd = currentHeight + image.ScaledHeight + diff + image.SpacingAfter;
}
From v5.2.1 it was line 2244 in PdfDocument.cs

Categories