Header, footer and large tables with iTextSharp - asp.net

I've added an header and a footer on my document by PdfPageEventHelper.
The document has several "large" tables populated at runtime.
I've tried to add those tables simply by "documen.Add(table)", but my header and my footer results overwritten.
I've already tried both methods to add the tables (WriteSelectedRows and document.Add(myPdfPtable).
Here is the code of the PageEventHelper:
private class MyPageEventHandler : PdfPageEventHelper
{
public iTextSharp.text.Image ImageHeader { get; set; }
public iTextSharp.text.Image ImageFooter { get; set; }
public override void OnEndPage(PdfWriter writer, Document document)
{
var fontintestazione = FontFactory.GetFont("Verdana", 10, Font.BOLD, BaseColor.LIGHT_GRAY);
var fontRight = FontFactory.GetFont("Verdana", 8, Font.BOLD, BaseColor.WHITE);
var fontFooter = FontFactory.GetFont("Verdana", 6, Font.NORMAL, BaseColor.BLUE);
float cellHeight = document.TopMargin;
Rectangle page = document.PageSize;
PdfPTable head = new PdfPTable(3);
head.TotalWidth = page.Width;
PdfPCell c = new PdfPCell(ImageHeader, true);
c.HorizontalAlignment = Element.ALIGN_LEFT;
c.FixedHeight = cellHeight;
c.Border = PdfPCell.NO_BORDER;
head.AddCell(c);
c = new PdfPCell(new Phrase("somePhrase", fontintestazione));
c.Border = PdfPCell.NO_BORDER;
head.AddCell(c);
c = new PdfPCell(new Phrase("someTextBlah", fontRight));
c.Border = PdfPCell.NO_BORDER;
c.HorizontalAlignment = 1;
c.BackgroundColor = new BaseColor(70, 130, 180);
head.AddCell(c);
head.WriteSelectedRows(0, -1, 10, page.Height - cellHeight + head.TotalHeight -30, writer.DirectContent);
PdfPTable footer = new PdfPTable(2);
footer.TotalWidth = 316f;
float[] cfWidths = new float[] { 2f, 1f };
footer.SetWidths(cfWidths);
PdfPCell cf = new PdfPCell(ImageFooter, true);
cf.HorizontalAlignment = Element.ALIGN_RIGHT;
cf.FixedHeight = cellHeight;
cf.Border = PdfPCell.NO_BORDER;
footer.AddCell(cf);
cf = new PdfPCell(new Phrase("someEndingText", fontFooter));
cf.HorizontalAlignment = Element.ALIGN_LEFT;
cf.Border = PdfPCell.NO_BORDER;
footer.AddCell(cf);
footer.WriteSelectedRows(0, -1, 10, 50, writer.DirectContent);
}
On my page, i simply do:
var document = new Document(PageSize.A4);
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(document, output);
iTextSharp.text.Image imageHeader = iTextSharp.text.Image.GetInstance(Server.MapPath("/images/header.ong"));
iTextSharp.text.Image imageFooter = iTextSharp.text.Image.GetInstance(Server.MapPath("/images/footer.png"));
MyPageEventHandler eve = new MyPageEventHandler
{
ImageHeader = imageHeader ,
ImageFooter = imageFooter
};
writer.PageEvent = eve;
document.Open();
//adding a table
PdfPTable cvTable = new PdfPtable(3);
cvTable.TotalWidth = document.PageSize.Width;
PdfPCell hCell = new PdfPCell(new Phrase("Jobs By User", aCustomFont));
cvTable.AddCell(hCell);
for(int i = 0; i < myTable.Records.Count; i++)
{
PdfPCell idCell = new PdfPCell(new Phrase(myTable.Records[i]._id, aFont));
cvTable.Add(idCell);
//same stuff for other fields of table
}
//first attempt.... failed:
document.Add(cvTable) //<- header and footer are overwritten by table
//second attempt..... failed too...
cvTable.WriteSelectedRows(0, -1, 10, myPoisition, writer.DirectContent);
//kind of fail...:
//the table is large and need more pages. It is trunked on the first page and overwrite
//the footer.

In your OnEndPage method you have this line:
head.WriteSelectedRows(0, -1, 10, page.Height - cellHeight + head.TotalHeight - 30, writer.DirectContent);
That code correctly calculates where to put content based on the page's height and top margin but also includes a magical 30 in there which is causing the header to be drawn on top of the table. Change it to this and your header will be fine.
head.WriteSelectedRows(0, -1, 10, page.Height - cellHeight + head.TotalHeight, writer.DirectContent);
I'm guessing that that 30 is trying to include some padding between your header and the table itself. What I would recommend is actually changing the document's margins themselves in the main code:
document.SetMargins(document.LeftMargin, document.RightMargin, document.TopMargin + 30, document.BottomMargin);
And then accounting for that in the OnEndPage method:
float cellHeight = document.TopMargin - 30;
Your footer code doesn't actually account for the bottom margin and just draws it at 50 so this will always overlap. The quick fix would be to change it to:
footer.WriteSelectedRows(0, -1, 10, footer.TotalHeight, writer.DirectContent);
This will at least get the footer bottom-aligned. If you want some more padding like above just adjust the document margins again:
document.SetMargins(document.LeftMargin, document.RightMargin, document.TopMargin + 30, document.BottomMargin + 30);

Related

Is it possible to export 2 OxyPlot PlotModels in one .png file?

Currently I am able to export one PlotModel as a .png at a time, using:
public void CreatePNG(PlotModel plotModel, string fileName, Stream stream)
{
var pngExporter = new PngExporter { Width = 600, Height = 400, Background = OxyColors.White };
pngExporter.Export(plotModel, stream);
}
Here is the .png output of the PlotModel
Is there a way to export 2 PlotModels such that they look like this in the .png file?
Or, can I concatenate 2 .png files??
I figured out how to export multiple OxyPlot plots in a .png file, by converting them into Bitmap.
Here a sample code:
var stream1 = new MemoryStream();
var stream2 = new MemoryStream();
var pngExporter = new PngExporter {Width = 600, Height = 400, Background = OxyColors.White};
var pngExporter2 = new PngExporter {Width = 600, Height = 400, Background = OxyColors.White};
pngExporter.Export(plotModel1, stream1);
pngExporter2.Export(plotModel2, stream2);
System.Drawing.Bitmap b1 = new System.Drawing.Bitmap(Image.FromStream(stream1));
System.Drawing.Bitmap b2 = new System.Drawing.Bitmap(Image.FromStream(stream2));
System.Drawing.Bitmap img = new System.Drawing.Bitmap(600, 800);
Graphics g = Graphics.FromImage(img);
g.DrawImage(b1, 0, 0);
g.DrawImage(b2, 0, 400);
img.Save(stream.ToString());

How to add additionalIcons to the tile in a Band

I am developing Microsoft Band2 Apps, I want to add Additional icons to my app tile in a band, like setting tile in Band2. I followed the below code to add Additional icons to the tile
Guid pageguid = Guid.NewGuid();
var panel = new ScrollFlowPanel
{
Rect = new PageRect(0, 0, 260, 128),
};
panel.Elements.Add(new FlowPanel
{
Rect = new PageRect(0, 0, 32, 32),
HorizontalAlignment = Microsoft.Band.Tiles.Pages.HorizontalAlignment.Center,
});
panel.Elements.Add(new Icon
{
HorizontalAlignment = Microsoft.Band.Tiles.Pages.HorizontalAlignment.Center,
Rect= new PageRect(0, 0, 32, 32),
ColorSource= ElementColorSource.BandHighlight,
});
var layout = new PageLayout(panel);
BandTile tile = new BandTile(tileGuid)
{
Name = "EmergencyHelp ",
TileIcon = await LoadIcon("ms-appx:///Assets/User that is member of security group.png"),
SmallIcon = await LoadIcon("ms-appx:///Assets/User that is member of security groupSmall.png"),
};
int firstIconIndex = tile.AdditionalIcons.Count + 2; // First 2 are used by the Tile itself
tile.AdditionalIcons.Add(await LoadIconMethod(AdjustUriMethod("ms-appx:///Assets/User that is member of security groupSmall.png")));
pageLayoutData.ById<IconData>(3).IconIndex = (ushort)(firstIconIndex + 0);
tile.PageLayouts.Add(layout);
if (tile.TileId != null)
{
await client.TileManager.RemoveTileAsync(tile.TileId);
}
await client.TileManager.AddTileAsync(tile);
await client.TileManager.SetPagesAsync(
tileGuid,
new PageData(pageguid, 0, new TextButtonData(1, "Emergency")));
I am getting the exception as shown in below figure,

Process.start not working on server

I create a PDF file using itextsharp. It's created successfully and open with adobe reader 9 not in adobe reader 7 and 8. Please help me to fix this error.
This is my partial code :
try
{
//yourFont = BaseFont.CreateFont(Application.StartupPath + "/verdana.TTF", BaseFont.WINANSI, BaseFont.EMBEDDED);
pgSize = new iTextSharp.text.Rectangle(320, 455);
doc = new Document(pgSize, 15, 5, 12, 4);
fnt = new iTextSharp.text.Font(yourFont, 7, 3);
fnt1 = new iTextSharp.text.Font(yourFont, 5, 0);
fnt2 = new iTextSharp.text.Font(yourFont, 3, 2);
fnt3 = new iTextSharp.text.Font(yourFont, 4, 6);
PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("Payslip.pdf"), FileMode.Create));
//PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("Payslip.pdf"), FileMode.Create)); //Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Payslip.pdf"
doc.Open();
DataView DView = (DataView)Session["data_value"];
dtData = DView.ToTable();
dr = dtData.Select("fldemp_no='" + Session["EmployeeID"].ToString() + "'");
doc.NewPage();
iTextSharp.text.Image ObjImg = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Bin/Head.png"));
ObjImg.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
ObjImg.ScaleToFit(220f, 150f);
ObjImg.SpacingBefore = 13f;
ObjImg.SpacingAfter = 1f;
doc.Add(ObjImg);
maintable = new PdfPTable(1);
cell = new PdfPCell(new Phrase("Pay Slip for the month of " + dr[0]["fldmonth"].ToString(), fnt1));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.Border = 0;
maintable.AddCell(cell);
doc.Add(maintable);
maintable = new PdfPTable(2);
empdetright = new PdfPTable(2);
empdetleft = new PdfPTable(2);
cell = new PdfPCell(new Phrase("Emp No", fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
cell = new PdfPCell(new Phrase(": " + dr[0]["fldemp_no"].ToString(), fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
cell = new PdfPCell(new Phrase("Emp Name", fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
cell = new PdfPCell(new Phrase(": " + dr[0]["fldempname"].ToString(), fnt1));
cell.Border = 0;
empdetright.AddCell(cell);
.......
doc.Close();
Process.Start(Server.MapPath("Payslip.pdf"));
The above code is run on local machine not on server. Please help me to fix this error..
Process.Start will attempt to open the file in the computer it is running (the server).
This is unlikely to be what you want. You should be uploading the file to the browser and let it decide (using Response.WriteFile, for instance).

Argument out of Exception unhandled in MigraDoc

static void Main(string[] args)
{
string saveFileAs = "D:\\Hello.pdf";
Program p = new Program();
Document doc = p.CreateDocument();
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
renderer.Document = doc;
renderer.RenderDocument();
renderer.PdfDocument.Save("D:\\Hello.pdf");
Process.Start(saveFileAs);
}
public Document CreateDocument()
{
// Create a new MigraDoc document
this.document = new Document();
this.document.Info.Title = "A sample invoice";
this.document.Info.Subject = "Demonstrates how to create an invoice.";
this.document.Info.Author = "Chandana Amarnath";
DefineStyles();
CreatePage();
FillContent();
return this.document;
}
void CreatePage()
{
// Each MigraDoc document needs at least one section.
Section section = this.document.AddSection();
// Put a logo in the header
Image image = section.Headers.Primary.AddImage("D:\\Cubes.jpg");
image.Height = "2.5cm";
image.LockAspectRatio = true;
image.RelativeVertical = RelativeVertical.Line;
image.RelativeHorizontal = RelativeHorizontal.Margin;
image.Top = ShapePosition.Top;
image.Left = ShapePosition.Right;
image.WrapFormat.Style = WrapStyle.Through;
// Create footer
Paragraph paragraph = section.Footers.Primary.AddParagraph();
// The following one prints at the footer;
paragraph.AddText("Aldata Inc.");
paragraph.Format.Font.Size = 9;
paragraph.Format.Alignment = ParagraphAlignment.Center;
// Create the text frame for the address
this.addressFrame = section.AddTextFrame();
this.addressFrame.Height = "3.0cm";
this.addressFrame.Width = "7.0cm";
this.addressFrame.Left = ShapePosition.Left;
this.addressFrame.RelativeHorizontal = RelativeHorizontal.Margin;
this.addressFrame.Top = "5.0cm";
this.addressFrame.RelativeVertical = RelativeVertical.Page;
// Put sender in address frame
paragraph = this.addressFrame.AddParagraph("Aldata-Apollo Inc.");
paragraph.Format.Font.Name = "Times New Roman";
paragraph.Format.Font.Size = 7;
paragraph.Format.SpaceAfter = 3;
// Add the print date field
paragraph = section.AddParagraph();
paragraph.Format.SpaceBefore = "8cm";
paragraph.Style = "Reference";
paragraph.AddFormattedText("Section Comparator", TextFormat.Bold);
paragraph.AddTab();
paragraph.AddText("Date: ");
paragraph.AddDateField("dd.MM.yyyy");
// Create the item table
this.table = section.AddTable();
this.table.Style = "Table";
this.table.Borders.Color = Color.Parse("Black");
this.table.Borders.Width = 0.25;
this.table.Borders.Left.Width = 0.5;
this.table.Borders.Right.Width = 0.5;
this.table.Rows.LeftIndent = 0;
//************ Before you can add a row, you must define the columns **********
Column column = this.table.AddColumn("4cm");
column.Format.Alignment = ParagraphAlignment.Center;
column = this.table.AddColumn("3cm");
column.Format.Alignment = ParagraphAlignment.Right;
// Create the header of the table
Row row = table.AddRow();
row.HeadingFormat = true;
row.Format.Alignment = ParagraphAlignment.Center;
row.Format.Font.Bold = true;
row.Shading.Color = Color.Parse("White");
row.Cells[0].AddParagraph("Added");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Center;
row.Cells[0].MergeRight = 3;
row = table.AddRow();
row.HeadingFormat = true;
row.Format.Alignment = ParagraphAlignment.Center;
row.Format.Font.Bold = true;
row.Cells[0].AddParagraph("Deleted Items");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Left;
row.Cells[0].MergeRight = 3;
this.table.SetEdge(0, 0, 2, 3, Edge.Box, BorderStyle.Single, 0.75, Color.Empty);
}
void FillContent()
{
string xmlFileName = "C:\\Section.xml";
XPathDocument xPathDocument = new XPathDocument(xmlFileName);
XPathNavigator item = xPathDocument.CreateNavigator();
XPathNodeIterator iter = item.Select("/Hello/*");
while (iter.MoveNext())
{
string name = iter.Current.Name;
item = iter.Current;
Row row1 = this.table.AddRow();
Row row2 = this.table.AddRow();
row1.TopPadding = 1.5;
row1.Cells[0].Shading.Color = Color.Parse("Gray");
row1.Cells[0].VerticalAlignment = VerticalAlignment.Center;
row1.Cells[0].MergeDown = 1;
row1.Cells[1].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[1].MergeRight = 3;
row1.Cells[0].AddParagraph(item.ToString());
Console.WriteLine(name + "\t:" +item);
}
Console.ReadKey();
}
I am writing code for generating my report in PDF using MigraDoc. I have downloaded the code from PDFSharp site. The following has 3 functions DefineStyles(), CreatePage(), FillContent(). I made changes in function CreatePage(), FillContent(); But when I am running the program I am getting error saying
Argument out of Exception:
Specified argument was out of the range of valid values.
In the CreatePage() I added 2 rows and 2 columns to a table. And in the FillContent() function I read my XML file. But I am unable to find where I am crossing my index range.
SOLVED
The problem is when I am setting the table.SetEdge(...). I am accessing the columns that I have not created.
Thank u all .. :)
At this step I was setting the rows that are not yet created.
this.table.SetEdge(0, 0, 2, 3, Edge.Box, BorderStyle.Single, 0.75, Color.Empty);
Instead of 3 which are the number of rows I should use 2.

Itextsharp: Is There Any Way To Copy Links When Import Pages?

I'm working on a project where i need to edit pdf's before display it
I need
add a watermark
edit permissions ( lock for avoid 'copy/paste' and 'save as' )
edit viewer preferences
And i did it... and work fine except for one thing, the links in the original file does not work in the new file... any idea?
NOTE: Actually, this is my code ( i'm using itextsharp )
private void loadPdf()
{
if (Request.QueryString.HasKeys())
{
if (Request.QueryString.GetKey(0) == "thepath" && Request.QueryString.GetKey(1) == "isprintable" && Request.QueryString.GetKey(2) == "type")
{
#region kuak
Document doc = new Document();
PdfReader pdfReader = new PdfReader(Request.QueryString["thepath"]);
using (MemoryStream memoryStream = new MemoryStream())
{
PdfWriter pdfWriter = PdfWriter.GetInstance(doc, memoryStream);
pdfWriter.ViewerPreferences = PdfWriter.PageModeUseOutlines;
//pdfWriter.ViewerPreferences = PdfWriter.PageLayoutTwoColumnLeft; /// Despliega el docuemnto en pares de hojas
pdfWriter.ViewerPreferences = PdfWriter.PageLayoutOneColumn;
pdfWriter.ViewerPreferences = PdfWriter.HideToolbar;
//pdfWriter.ViewerPreferences = PdfWriter.HideWindowUI; /// quita los scrollbars y el panel de la derecha qur contiene los bookmarks y las buskedas dentro del pdf
if (Request.QueryString["isprintable"] == "n")
{
pdfWriter.ViewerPreferences = PdfWriter.HideMenubar;
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
pdfWriter.SetEncryption(null, encoding.GetBytes("mYpAssss"), 0, PdfWriter.STRENGTH40BITS);
}
doc.Open();
PdfContentByte pdfContentByte = pdfWriter.DirectContent;
doc.AddDocListener(pdfWriter);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
//doc.SetPageSize(pdfReader.GetPageSize(page));
doc.SetPageSize(pdfReader.GetPageSizeWithRotation(page));
doc.NewPage();
PdfImportedPage pdfImportedPage = pdfWriter.GetImportedPage(pdfReader, page);
int rot = pdfReader.GetPageRotation(page);
if (rot == 90 || rot == 270)
pdfContentByte.AddTemplate(pdfImportedPage, 0, -1.0F, 1.0F, 0, 0, pdfReader.GetPageSizeWithRotation(page).Height);
else
pdfContentByte.AddTemplate(pdfImportedPage, 1.0F, 0, 0, 1.0F, 0, 0);
string theId = findId();
if (isWatermarkNeeded(theId))
{
#region ADD TEXT WATERMARK
//pdfContentByte.BeginText();
//iTextSharp.text.Rectangle pageSize = pdfReader.GetPageSizeWithRotation(page);
//BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, System.Text.Encoding.ASCII.EncodingName, false);
//pdfContentByte.SetFontAndSize(baseFont, 200);
//BaseColor baseColor = new BaseColor(255, 0, 0, 20);
//pdfContentByte.SetColorFill(baseColor);
//float textAngle = (float)GetHypotenuseAngleInDegreesFrom(pageSize.Height, pageSize.Width);
//pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "DRAFT", 350, pageSize.Height / 2, textAngle);
//pdfContentByte.EndText();
#endregion
#region ADD IMAGE WATERMARK
string fechaExp = "Este documento vence: " + GetExpirationDate(theId).ToShortDateString();
pdfContentByte.BeginText();
//iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(Server.MapPath("~/images/watermark3.png"));
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ImageCheck.CreatePicture(#"C:\Users\myUser\Desktop\watermark.png", fechaExp).ToArray());
img.SetAbsolutePosition(0, 0);
pdfContentByte.AddImage(img);
pdfContentByte.EndText();
#endregion
}
}
pdfReader.Close();
doc.Close();
byte[] content = memoryStream.ToArray();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", content.Length.ToString());
Response.BinaryWrite(content);
}
#endregion
}
else
{
//hay querystring pro no corresponden con los que se necesita
}
}
else
{
//no se enviaron los querystring
}
}
You have to get the links from original PDF
var links = reader.GetLinks(pageNumber);
And write them to the new PDF
foreach (var link in links)
{
var annotation = link.CreateAnnotation(pdfWriter);
writer.AddAnnotation(annotation);
}

Resources