我正在尝试使用iTextSharp生成PDF文件,因此我设法生成我的PDF文件,如下所示:
这是我的代码:
在我的控制器中,我从String(JSON格式)获取数据< ---- String screendata:
[HttpPost]
public void GenaraleExportPDF(String screendata,String monTitre,String file)
{
ExportManager export = new ExportManager();
String MapPath = Server.MapPath("~/Content/");
string filepath = MapPath + file;
//Appel Methodes Export Manager pour generer PDF
export.GenererPdfJSON(screendata, monTitre, MapPath, file);
//Ajout Response : transmitfile self buffers
Response.Buffer = false;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + file);
Response.TransmitFile(filepath);
Response.End();
}
其他功能:
生成表格的标题和数据 - > AjoutHeaderDataTablePdf():
public PdfPTable AjoutHeaderDataTablePdf(object[] tableObjet, PdfPTable table, iTextSharp.text.Font fntTableFontHdr)
{
table.HeaderRows = 2;
table.HorizontalAlignment = 0;
table.TotalWidth = 500f;
table.LockedWidth = true;
float[] widths = new float[] { 60f, 40f, 60f, 40f, 60f, 80f};
table.SetWidths(widths);
//Font Color
BaseColor ForeGroundmyColorHeader = WebColors.GetRGBColor("#FFFFFF");
BaseColor ForeGroundmyColorOthers = WebColors.GetRGBColor("#232323");
BaseColor BackGroundmyColor = WebColors.GetRGBColor("#32A3E0");
BaseColor BackGroundmyColorOther1 = WebColors.GetRGBColor("#D8E4FD");
BaseColor BackGroundmyColorOther2 = WebColors.GetRGBColor("#FFFFFF");
var FontHeader = FontFactory.GetFont("Times New Roman", 9, ForeGroundmyColorHeader);
var FontOthers = FontFactory.GetFont("Times New Roman", 8, ForeGroundmyColorOthers);
var borderColor = WebColors.GetRGBColor("#E4E4E4");
var borderWidth =0f;
/***Begin Header***/
/******Fin Header******/
// Ajout Headers columnsName
foreach (var o in tableObjet)
{
Dictionary<string, object> dictionary = (Dictionary<string, object>)o;
foreach (KeyValuePair<string, object> pair in dictionary)
{
PdfPCell CellOneHdr2 = new PdfPCell(new Phrase(pair.Key, FontHeader));
CellOneHdr2.BackgroundColor = BackGroundmyColor;
CellOneHdr2.BorderColorLeft = borderColor;
CellOneHdr2.BorderColorRight = borderColor;
CellOneHdr2.BorderColorTop = borderColor;
CellOneHdr2.BorderColorBottom = borderColor;
CellOneHdr2.BorderWidthLeft = borderWidth;
CellOneHdr2.BorderWidthRight = borderWidth;
CellOneHdr2.BorderWidthTop = borderWidth;
CellOneHdr2.BorderWidthBottom = borderWidth;
CellOneHdr2.PaddingTop = 6f;
CellOneHdr2.PaddingLeft = 5f;
CellOneHdr2.FixedHeight = 26f;
table.AddCell(CellOneHdr2);
}
break;
}
//Ajout de contenu de cellules
int count = 0;
BaseColor BackGroundmyColorOtherX;
for (int ii = 0; ii < 5; ii++)
{
foreach (var o in tableObjet)
{
Dictionary<string, object> dictionary = (Dictionary<string, object>)o;
if (count % 2 == 0)
BackGroundmyColorOtherX = BackGroundmyColorOther1;
else
BackGroundmyColorOtherX = BackGroundmyColorOther2;
foreach (KeyValuePair<string, object> pair in dictionary)
{
PdfPCell CellOneHdr2 = new PdfPCell(new Phrase(pair.Value.ToString(), FontOthers));
CellOneHdr2.BackgroundColor = BackGroundmyColorOtherX;
CellOneHdr2.FixedHeight = 23f;
CellOneHdr2.BorderColorLeft = borderColor;
CellOneHdr2.BorderColorRight = borderColor;
CellOneHdr2.BorderColorTop = borderColor;
CellOneHdr2.BorderColorBottom = borderColor;
CellOneHdr2.BorderWidthLeft = borderWidth;
CellOneHdr2.BorderWidthRight = borderWidth;
CellOneHdr2.BorderWidthTop = borderWidth;
CellOneHdr2.BorderWidthBottom = borderWidth;
CellOneHdr2.PaddingTop = 6f;
CellOneHdr2.PaddingLeft = 5f;
table.AddCell(CellOneHdr2);
}
count++;
}
}
table.HorizontalAlignment = 1;
return table;
}
生成表格标题 - &gt; TitreTablePdfCentre():
public PdfPTable TitreTablePdfCentre(int NbrCol, String Titre)
{
BaseColor ForeGroundmyColorHeader = WebColors.GetRGBColor("#FFFFFF");
BaseColor BackGroundmyColorHeader = WebColors.GetRGBColor("#32A3E0");
var borderColor = WebColors.GetRGBColor("#E4E4E4");
var borderWidth = 0.1f;
var FontHeader = FontFactory.GetFont("Times New Roman", 12, ForeGroundmyColorHeader);
//Creer PdfTable contenant NbrCol colonnes
PdfPTable table = new PdfPTable(NbrCol);
table.HeaderRows = 2;
//Ajouter un Titre en haut du fichier
PdfPCell cell = new PdfPCell(new Phrase(Titre, FontHeader));
// fusionner les NbrCol celllules en une seul cellule
cell.Colspan = NbrCol;
//Metre au centre : 0=Left, 1=Centre, 2=Right
cell.HorizontalAlignment = 1;
// Ajout La cellule à Pdftable
/**Style**/
cell.FixedHeight = 30f;
cell.PaddingTop = 6f;
cell.BackgroundColor = BackGroundmyColorHeader;
cell.BorderColorLeft = borderColor;
cell.BorderColorRight = borderColor;
cell.BorderColorTop = borderColor;
cell.BorderColorBottom = borderColor;
cell.BorderWidthLeft = borderWidth;
cell.BorderWidthRight = borderWidth;
cell.BorderWidthTop = borderWidth;
cell.BorderWidthBottom = borderWidth;
table.AddCell(cell);
table.HorizontalAlignment = 1;
return table;
}
从Json生成数据 - &gt; GenererPdfJSON():
public void GenererPdfJSON(String screendata, String Titre, String MapPath, String file)
{
//Convertir String JSON to Table object[]
object[] tableObjet = TbaleJSON(screendata);
//Retourne Nbr Lignes Object
int nbrlignes = NbrLignesTableJSON(tableObjet);
//Calcul de nombre de colonnes de tableObjet
int nbrcol = NbrColonnesTableJSON(tableObjet);
//Creer PdfTable contenant nbrcol colonnes en heut de la feuille
PdfPTable table = TitreTablePdfCentre(nbrcol, Titre);
table.HeaderRows = 2;
Document document = new Document();
//Ajout de qlq Style
iTextSharp.text.Font fntTableFontHdr = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
//Lien Physique Server.MapPath("~/Content/") + fichierpdf.pdf
string filepath = MapPath + file;
//Ecrire les données dans le fichier
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filepath, FileMode.Create));
//Ouvrir le document
document.Open();
/**pagination***/
Paragraph para = new Paragraph("Hello world. Checking Header Footer", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 22));
para.Alignment = Element.ALIGN_CENTER;
document.Add(para);
//*****************//
//Ajouter le noms colonnes et les donnees dans les cellules avec Style fntTableFontHdr
table = AjoutHeaderDataTablePdf(tableObjet, table, fntTableFontHdr);
document.Add(table);
document.Close();
}
我的问题是我想为每个页面创建页眉和页脚以显示页码,标题,......
答案 0 :(得分:0)
可以通过覆盖PdfPageEventHelper添加页脚和标题。通过将类的实例添加到PdfWriters页面事件,需要将以下代码与当前文档相关联,例如writer.PageEvent = new PageEventHelper();
。作为侧点,必须在文档打开之前放置。
调用document.NewPage()
时调用OnEndPage,并在指定位置添加当前页码。还要添加&#34; Y&#34;我们需要等到文档关闭才能确保获得正确的页数。
public class PageEventHelper : PdfPageEventHelper
{
PdfContentByte cb;
PdfTemplate template;
public override void OnOpenDocument(PdfWriter writer, Document document)
{
cb = writer.DirectContent;
template = cb.CreateTemplate(width, height);
}
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
int pageN = writer.PageNumber;
String text = "Page " + pageN.ToString() + " of ";
Rectangle pageSize = document.PageSize;
cb.BeginText();
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12F);
cb.SetTextMatrix(Width, Height);
cb.ShowText(text);
cb.EndText();
//Add the template to each page so we can add the total page number later
cb.AddTemplate(template, Width, Height);
}
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
template.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12F);
template.BeginText();
template.SetTextMatrix(0, 0);
//Add the final page number.
template.ShowText("" + (writer.PageNumber - 1));
//This will write the number on all templates on all pages
template.EndText();
}
}
有关PdfPageEvenHelper类的更多详细信息,请访问http://api.itextpdf.com/itext/com/itextpdf/text/pdf/PdfPageEventHelper.html。这是用Java编写的,但很容易在c#中使用相同的代码。
此原则可用于通过使用不同的模板添加页脚和标题。