使用ABCpdf
DLL,在文本区域中可以编写HTML代码,并在单击按钮时显示相应的PDF。可以轻松下载ABCpdf
试用版,添加链接以下载ABCpdf
DLL。https://www.websupergoo.com/download.htm
index.cshtml
@using (Html.BeginForm("covertopdf", "simple", FormMethod.Post))
{
<p style="margin-top:50px">
Input Html: @Html.TextArea("Htmlcontent", new { @class = "form-control",@cols="160" , @rows="20"})<br />
<input type="submit" class="btn-primary" value="Convertopdf" />
</p>
}
SimpleController.cs
public class SimpleController : Controller
{
public class FileViewModel
{
public byte[] Content { get; set; }
public string Extension { get; set; }
public string FileName { get; set; }
}
[HttpPost]
[ValidateInput(false)]
public FileStreamResult covertopdf(string Htmlcontent)
{
var result = ExecuteAction(() =>
{
var fileViewmodel = new FileViewModel
{
Content = ConvertHtmlToPdf(Htmlcontent),
Extension = "application/pdf",
FileName = "Policy Information.pdf"
};
return fileViewmodel;
}, "covertopdf");
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
Stream stream = new MemoryStream(result.Content);
return new FileStreamResult(stream, "application/pdf")
{
};
}
public T ExecuteAction<T>(Func<T> action, string method)
{
try
{
return action.Invoke();
}
catch (Exception ex)
{
return default(T);
}
}
protected byte[] ConvertHtmlToPdf(string html, string header = null, string footer = null, bool isPageNumberInFooter = false)
{
var doc = new Doc();
if (header == null && footer == null)
doc.Rect.Inset(20, 20);
else
doc.Rect.String = "0 70 600 760";
int theId = doc.AddImageHtml(html);
while (true)
{
if (!doc.Chainable(theId))
break;
doc.Page = doc.AddPage();
theId = doc.AddImageToChain(theId);
}
var count = doc.PageCount;
if (footer != null)
{
var newfooter = "";
doc.Rect.String = "40 20 580 50";
for (int i = 1; i <= count; i++)
{
doc.PageNumber = i;
if (isPageNumberInFooter)
{
newfooter = footer.Replace("PageNumber", "Page " + i.ToString() + " of " + count.ToString());
int id = doc.AddImageHtml(newfooter);
while (true)
{
if (!doc.Chainable(id))
break;
id = doc.AddImageToChain(id);
}
}
else
doc.AddText(footer);
}
}
for (int i = 1; i <= doc.PageCount; i++)
{
doc.PageNumber = i;
doc.Flatten();
}
var pdf = doc.GetData();
doc.Clear();
return pdf;
}
}