繁体   English   中英

如何在实体框架工作中使用 c# 将任何类型的文本文件转换为 asp.net web api 中的 PDF 文件?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM