在我的项目中,我使用MVC4,C#和itextsharp从html生成pdf。我需要插入带有徽标和模板名称的标题,以及带有分页的页脚(页码/总页数)。我完成了页脚,我已经使用此代码将页脚添加到pdf文件:
public static byte[] AddPageNumbers(byte[] pdf)
{
MemoryStream ms = new MemoryStream();
ms.Write(pdf, 0, pdf.Length);
// we create a reader for a certain document
PdfReader reader = new PdfReader(pdf);
// we retrieve the total number of pages
int n = reader.NumberOfPages;
// we retrieve the size of the first page
Rectangle psize = reader.GetPageSize(1);
// step 1: creation of a document-object
Document document = new Document(psize, 50, 50, 50, 50);
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, ms);
// step 3: we open the document
document.Open();
// step 4: we add content
PdfContentByte cb = writer.DirectContent;
int p = 0;
Console.WriteLine("There are " + n + " pages in the document.");
for (int page = 1; page <= reader.NumberOfPages; page++)
{
document.NewPage();
p++;
PdfImportedPage importedPage = writer.GetImportedPage(reader, page);
cb.AddTemplate(importedPage, 0, 0);
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.BeginText();
cb.SetFontAndSize(bf, 10);
cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, +p + "/" + n, 44, 7, 0);
cb.EndText();
}
// step 5: we close the document
document.Close();
return ms.ToArray();
}
}
如果您需要有关此代码的任何解释,请告诉我。
我尝试对标题使用相同的方法,但我的网站徽标覆盖了pdf页面的现有内容。然后我尝试使用此代码,但没有运气:(
public _events(string TemplateName,string ImgUrl)
{
this.TempName = TemplateName;
this.ImageUrl = ImgUrl;
}
private string TempName = string.Empty;
private string ImageUrl = string.Empty;
public override void OnEndPage(PdfWriter writer, Document doc)
{
//Paragraph footer = new Paragraph("THANK YOU ", FontFactory.GetFont(FontFactory.TIMES, 10, iTextSharp.text.Font.NORMAL));
Paragraph header = new Paragraph("Template Name:" + TempName + " " +DateTime.UtcNow, FontFactory.GetFont(FontFactory.TIMES, 10, iTextSharp.text.Font.NORMAL));
//adding image (logo)
string imageURL = HttpContext.Current.Server.MapPath("~/Content/images.jpg");
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);
//Resize image depend upon your need
jpg.ScaleToFit(140f, 120f);
//Give space before image
jpg.SpacingBefore = 10f;
//Give some space after the image
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.ALIGN_LEFT;
header.Alignment = Element.ALIGN_TOP;
PdfPTable headerTbl = new PdfPTable(1);
headerTbl.TotalWidth = 400;
headerTbl.HorizontalAlignment = Element.ALIGN_CENTER;
PdfPCell cell11 = new PdfPCell(header);
PdfPCell cell2 = new PdfPCell(jpg);
cell2.Border = 0;
cell11.Border = 0;
cell11.PaddingLeft = 10;
cell2.PaddingLeft = 10;
headerTbl.AddCell(cell11);
headerTbl.AddCell(cell2);
headerTbl.WriteSelectedRows(0, -1, doc.LeftMargin, doc.PageSize.Height - 10, writer.DirectContent);
}
}
这是我的Action方法,它将pdf文件作为响应返回。我已经使用过这个课了。道歉可能是我应该在我的问题开头发布。
[HttpGet]
[HandleException]
public ActionResult GenerateLeadProposalPDF()
{
TempData.Keep();
long LeadId = Convert.ToInt64(TempData["Leadid"]);
long EstimateId = Convert.ToInt64(TempData["Estimateid"]);
long ProposalTemplateId = Convert.ToInt64(TempData["ProposalTemplateId"]);
Guid SubscriberId = SessionManagement.LoggedInUser.SubscriberId;
var data = this._LeadEstimateAPIController.GetLeadProposalDetails(LeadId, EstimateId, ProposalTemplateId, SubscriberId);
System.Text.StringBuilder strBody = new System.Text.StringBuilder("");
string SubscriberProjectBody = this.ControllerContext.RenderRazorViewToString(ViewData, TempData, "~/Areas/Subscriber/Views/Shared/_GenerateProposalTemplate.cshtml", data);
string Header = this.ControllerContext.RenderRazorViewToString(ViewData, TempData, "~/Areas/Subscriber/Views/Shared/_HeaderGenerateProposals.cshtml", data);
string styleCss = System.IO.File.ReadAllText(Server.MapPath("~/ProposalDoc_CSS.txt"));
strBody.Append(@"<html><head><title></title> </head>");
strBody.Append(@"<body lang=EN-US style='tab-interval:.5in'>");
// strBody.Append(Header);
strBody.Append(SubscriberProjectBody);
strBody.Append(@"</body></html>");
String htmlText = strBody.ToString();
Document document3 = new Document(PageSize.A4, 36, 36, 36, 36);
_events e = new _events(data.objProposalLeadDetailsModel.ProposalFullName,"test");
string filePath = HostingEnvironment.MapPath("~/");
filePath = filePath + "pdf-.pdf";
var stream=new FileStream(filePath, FileMode.Create);
var objPdfWriter= PdfWriter.GetInstance(document3, stream);
document3.Open();
objPdfWriter.PageEvent = e;
iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document3);
hw.Parse(new StringReader(htmlText));
document3.Close();
var result = System.IO.File.ReadAllBytes(filePath);
var abd = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var streamArray = ReadFully(abd);
var streamFile = AddPageNumbers(streamArray);
// Response.End();
string contentType = "application/pdf";
return File(streamFile, contentType, "LeadProposal.pdf");
}
任何建议或帮助将不胜感激,请帮助我,提前谢谢:)
在_events类中的一些变化后,我得到了我想要的东西,但可能是它不是正确的方法,但现在它为我工作:)
public class _events : PdfPageEventHelper
{
public _events(string TemplateName,string ImgUrl)
{
this.TempName = TemplateName;
this.ImageUrl = ImgUrl;
}
private string TempName = string.Empty;
private string ImageUrl = string.Empty;
public override void OnEndPage(PdfWriter writer, Document doc)
{
Paragraph PTempName = new Paragraph("Template Name:" + TempName, FontFactory.GetFont(FontFactory.TIMES, 10, iTextSharp.text.Font.NORMAL));
Paragraph PDate = new Paragraph(DateTime.UtcNow.ToShortDateString(), FontFactory.GetFont(FontFactory.TIMES, 10, iTextSharp.text.Font.NORMAL));
//adding image (logo)
string imageURL = "http://108.168.203.227/PoologicApp/Content/Bootstrap/images/logo.png";//HttpContext.Current.Server.MapPath("~/Content/images.jpg");
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);
//Resize image depend upon your need
jpg.ScaleToFit(70f, 120f);
//Give space before image
//jpg.SpacingBefore = 10f;
//Give some space after the image
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.ALIGN_TOP;
PTempName.Alignment = Element.ALIGN_TOP;
PDate.Alignment = Element.ALIGN_TOP;
PdfPTable headerTbl = new PdfPTable(3);
headerTbl.TotalWidth = 600;
headerTbl.HorizontalAlignment = Element.ALIGN_TOP;
PdfPCell cell11 = new PdfPCell(PTempName);
PdfPCell cell3 = new PdfPCell(PDate);
PdfPCell cell2 = new PdfPCell(jpg);
cell2.Border = 0;
cell11.Border = 0;
cell3.Border = 0;
cell11.PaddingLeft = 10;
cell3.PaddingLeft = 10;
cell2.PaddingLeft = 10;
headerTbl.AddCell(cell11);
headerTbl.AddCell(cell3);
headerTbl.AddCell(cell2);
headerTbl.WriteSelectedRows(0, -1, doc.LeftMargin, doc.PageSize.Height - 4, writer.DirectContent);
}
}