/// <summary>
/// word转pdf 免费版 25个table,10page
/// </summary>
/// <param name="sourcePath">word文件地址</param>
/// <param name="targetPath">pdf文件地址</param>
/// <returns></returns>
public static bool WordToPDF(string wordPath, string pdfPath)
{
bool result = false;
try
{
Spire.Doc.Document document = new Spire.Doc.Document();
document.LoadFromFile(wordPath, Spire.Doc.FileFormat.Docx);
ToPdfParameterList toPdf = new ToPdfParameterList();
toPdf.PdfConformanceLevel = Spire.Pdf.PdfConformanceLevel.Pdf_A1B;
document.SaveToFile(pdfPath, toPdf);
// 消除水印
PdfDocument doc = new PdfDocument(pdfPath);
doc.Pages.RemoveAt(doc.Pages.Count - 1);
doc.SaveToFile(pdfPath);
result = true;
}
catch (Exception e)
{
result = false;
}
return result;
}
[HttpPost]
[IdentifyDescription("all")]
[AllowAnonymous]
public HttpResponseMessage GetFileReply(JObject pars)
{
Reuse.CreateDir(StoragePath.zccl, out string fullPath, out string lastDir);
JArray arrOpinionIds = pars.GetValue("ids") as JArray;
long[] lArrOpinionIds = arrOpinionIds.Select(v => Reuse.GetId(v)).ToArray();
var mlOpinion = db.Queryable<application_information>().Where(v => lArrOpinionIds.Contains(v.ID)).ToList();
var name = "";
var wordBytes = mlOpinion.Select(m =>
{
var mUser = db.Queryable<users>().Where(v => v.ID == m.UserNameID).ToList().FirstOrDefault();
var mPorject = db.Queryable<project_information>().InSingle(m.ProjectID);
name = mUser.name + ".docx";
return new Tool.FileListModel
{
name = $"{mUser.name}的职称证明.docx",
bytes = Tool.ExportWordByReplaceString(HttpContext.Current.Server.MapPath("/Word/technical.docx"),
(xmlText, wordNewLine, newLine1, newLine2) => WatcloController.ReplaceOpinionWord(xmlText, wordNewLine, newLine1, newLine2, mPorject, m, mUser))
};
}).ToList();
if (mlOpinion.Count == 1)
{
using (FileStream fs = File.Create(fullPath + name))
{
}
File.WriteAllBytes(fullPath + name, wordBytes[0].bytes);
}
if (string.IsNullOrEmpty(name))
{
return null;
}
var path = System.Web.HttpContext.Current.Server.MapPath(StoragePath.zccl + name);
if (!File.Exists(path))
{
return null;
}
bool flag = false;
string fileExtension = Path.GetExtension(path);
string newPath = string.Empty;
string newUrl = string.Empty;
if (fileExtension == ".docx")
{
newPath = path.Substring(0, path.Length - 4) + "pdf";
newUrl = name.Substring(0, name.Length - 4) + "pdf";
flag = Tool.WordToPDF(path, newPath);
}
else if (fileExtension == ".doc")
{
newPath = path.Substring(0, path.Length - 3) + "pdf";
newUrl = name.Substring(0, name.Length - 3) + "pdf";
flag = Tool.WordToPDF(path, newPath);
}
if (flag)
{
FileStream fs = new FileStream(newPath, FileMode.Open);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
return Reuse.ReturnFile(buffer);
}
else
{
FileStream fs = new FileStream(path, FileMode.Open);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
return Reuse.ReturnFile(buffer);
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/81334f5687aad9b108d4e62d69e4bf22.png)