[英]how can i convert any kind of text file into a PDF file in asp.net web api using c# in entity frame work?
我想通過將文本文件從android
端轉換為base64
字符串將它們上傳到服務器,並使用asp.net
web api 將它們發送到服務器我再次在asp.net
web api 中解碼它們..但在實際將它們存儲到我的目錄我想將文件轉換為 pdf 文檔,無論它們是.docx
.txt
還是任何其他類型
我已經嘗試了以下代碼,但它給出了錯誤對象引用未設置為對象的實例我不知道如何解決它以及有什么問題
私有靜態字符串 saveFile(long id, string base64String) { 嘗試 {
String path = HttpContext.Current.Server.MapPath("~/images"); //Path
//Check if directory exist
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist
}
string imageName = "Documentation" + id + ".docx";
//set the image path
string imgPath = Path.Combine(path, imageName);
byte[] imageBytes = Convert.FromBase64String(base64String);
File.WriteAllBytes(imgPath, imageBytes);
Word2Pdf objWordPDF = new Word2Pdf();
object FromLocation = path+"\\"+imageName;
string FileExtension = Path.GetExtension(imageName);
string ChangeExtension = imageName.Replace(FileExtension, ".pdf");
if (FileExtension == ".doc" || FileExtension == ".docx")
{
object ToLocation = path + "\\" + ChangeExtension;
objWordPDF.InputLocation = FromLocation;
objWordPDF.OutputLocation = ToLocation;
objWordPDF.Word2PdfCOnversion();
}
return imageName;
}
catch (Exception ex)
{
return null;
}
}
此代碼沒有產生所需的結果,它返回一個空值作為圖像名稱
我實際上沒有一個可靠的答案,但根據我的經驗,我曾經使用 wkhtmltopdf 工具做過這個,這是一個將網頁轉換為 pdf 的外部工具。 邏輯是需要將您想要的任何內容作為 pdf 呈現到視圖中,並使用 wkhtmltopdf 的服務進行轉換。
這里的服務是我的樣本:
服務PDF.cs :
public class ServicePdf : IServicePdf
{
private readonly IConfiguration _configuration;
public ServicePdf(IConfiguration configuration)
{
_configuration = configuration;
}
public PdfGlobalOptions Options { set; get; }
/// <summary>
/// Pertmet la génération d'un fichier PDF
/// </summary>
/// <param name="url">l'url à convertir exp : http://www.google.fr</param>
/// <param name = "filename" > Nom du fichier pdf en output</param>
/// <returns>byte[] pdf en cas de succès, le message d'erreur en cas d'echec</returns>
public object GeneratePDF(string url, string filename)
{
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = _configuration.GetSection("wkhtmltopdf").GetSection("Path").Value + _configuration.GetSection("wkhtmltopdf").GetSection("Program").Value;
StringBuilder arguments = new StringBuilder();
arguments.Append("--page-size ");
arguments.Append("A4");
arguments.Append(" ");
if (Options.Orientation != PdfOrientation.Portrait)
{
arguments.Append("--orientation Landscape");
arguments.Append(" ");
}
if (Options.MarginLeft.HasValue)
{
arguments.Append("--margin-left ");
arguments.Append(Options.MarginLeft);
arguments.Append(" ");
}
if (Options.MarginTop.HasValue)
{
arguments.Append("--margin-top ");
arguments.Append(Options.MarginTop);
arguments.Append(" ");
}
if (Options.MarginRight.HasValue)
{
arguments.Append("--margin-right ");
arguments.Append(Options.MarginRight);
arguments.Append(" ");
}
if (Options.MarginBottom.HasValue)
{
arguments.Append("--margin-bottom ");
arguments.Append(Options.MarginBottom);
arguments.Append(" ");
}
if (Options.PageWidth.HasValue)
{
arguments.Append("--page-width ");
arguments.Append(Options.PageWidth);
arguments.Append(" ");
}
if (Options.PageHeight.HasValue)
{
arguments.Append("--page-height ");
arguments.Append(Options.PageHeight);
arguments.Append(" ");
}
if (Options.HeaderSpacing.HasValue)
{
arguments.Append("--header-spacing ");
arguments.Append(Options.HeaderSpacing);
arguments.Append(" ");
}
if (Options.FooterSpacing.HasValue)
{
arguments.Append("--footer-spacing ");
arguments.Append(Options.FooterSpacing);
arguments.Append(" ");
}
if (!string.IsNullOrEmpty(Options.Header))
{
arguments.Append("--header-html ");
arguments.Append(Options.Header);
arguments.Append(" ");
}
if (!string.IsNullOrEmpty(Options.Footer))
{
arguments.Append("--footer-html ");
arguments.Append(Options.Footer);
arguments.Append(" ");
}
arguments.Append(url);
arguments.Append(" ");
arguments.Append(System.IO.Path.GetTempPath());
arguments.Append(filename);
startInfo.Arguments = arguments.ToString();
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
process.StartInfo = startInfo;
process.Start();
var errors = process.StandardError.ReadToEnd();
if (System.IO.File.Exists(System.IO.Path.GetTempPath() + filename))
{
byte[] pdf = System.IO.File.ReadAllBytes(System.IO.Path.GetTempPath() + filename);
return pdf;
}
return errors;
}
}
IServicePDF.cs
public interface IServicePdf
{
object GeneratePDF(string url, string filename);
PdfGlobalOptions Options { set; get; }
}
PdfGlovalOptions.cs
public enum PdfOrientation { Landscape, Portrait };
public class PdfGlobalOptions
{
public float? MarginTop { get; set; }
public float? MarginLeft { get; set; }
public float? MarginBottom { get; set; }
public float? MarginRight { get; set; }
public float? PageWidth { get; set; }
public float? PageHeight { get; set; }
public string Header { get; set; }
public string Footer { get; set; }
public float? HeaderSpacing { get; set; }
public PdfOrientation Orientation { get; set; }
public float? FooterSpacing { get; set; }
}
最后在您的應用程序配置中添加必要的配置:
"wkhtmltopdf": {
"Path": "C:\\Program Files\\wkhtmltopdf\\bin\\",
"Program": "wkhtmltopdf.exe" }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.