C# 导出pdf(浏览器不预览直接下载)
一.接口部分的代码
[HttpGet]
public HttpResponseMessage ExportPdf(string id)
{
string pdfName = "";
//id 查询条件,根据实际情况修改即可
//pdfName 例如download.pdf
byte[] pdfData= _policyGapManagerService.ExportPdf(id, out pdfName);//获得pdf字节
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(pdfData)
};
result.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = pdfName
};
result.Content.Headers.ContentType =new MediaTypeHeaderValue("application/pdf");
return result;
}
二.返回pdfbyte数组
1.下载http模式的pdf文件(以ASP.NET为例,将PDF存在项目的目录下,可以通过http直接打开项目下的pdf文件)
#region 调用本地文件使用返回pdfbyte数组
/// <summary>
/// 调用本地文件使用返回pdfbyte数组
/// </summary>
/// <param name="srcPdfFile">‘D:\in2434341555551.pdf’</param>
/// <returns></returns>
public static byte[] GetSignaturePDFByte(string srcPdfFile)
{
using (FileStream fsRead = new FileStream(srcPdfFile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
int fsLen = (int)fsRead.Length;
byte[] hebyte = new byte[fsLen];
fsRead.Read(hebyte, , hebyte.Length);
return hebyte;
}
}
#endregion 调用本地文件使用返回pdfbyte数组
#region 从网站上下载pdf,转化为字节流
/// <summary>
/// 从网站上下载pdf,转化为字节流
/// </summary>
/// <param name="srcPdfFile">文件地址:'https://******/group2/M00/00/04/wKj-mlpcoZ2IUbK5AACrpaV6k98AAAB6gAAAAAAAKu9562.pdf'</param>
/// <returns></returns>
public static Byte[] GetByteByRemoteURL(string srcPdfFile)
{
byte[] arraryByte;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(srcPdfFile);
req.Method = "GET";
using (WebResponse wr = req.GetResponse())
{
StreamReader responseStream = new StreamReader(wr.GetResponseStream(), Encoding.UTF8);
int length = (int)wr.ContentLength;
byte[] bs = new byte[length];
HttpWebResponse response = wr as HttpWebResponse;
Stream stream = response.GetResponseStream();
//读取到内存
MemoryStream stmMemory = new MemoryStream();
byte[] buffer1 = new byte[length];
int i;
//将字节逐个放入到Byte 中
while ((i = stream.Read(buffer1, , buffer1.Length)) > )
{
stmMemory.Write(buffer1, , i);
}
arraryByte = stmMemory.ToArray();
stmMemory.Close();
}
return arraryByte;
}
#endregion 从网站上下载pdf,转化为字节流
#region 从网站上下载文件,保存到其他路径
/// <summary>
/// 从网站上下载文件,保存到其他路径
/// </summary>
/// <param name="pdfFile">文件地址</param>
/// <param name="saveLoadFile">保存文件路径:D:\12221.pdf</param>
/// <returns></returns>
public string SaveRemoteFile( string saveLoadFile , string pdfFile)
{
//bool flag = false;
var f = saveLoadFile + Guid.NewGuid().ToString("D") + ".pdf";
Uri downUri = new Uri(pdfFile);
//建立一个WEB请求,返回HttpWebRequest对象
HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(downUri);
//流对象使用完后自动关闭
using (Stream stream = hwr.GetResponse().GetResponseStream())
{
//文件流,流信息读到文件流中,读完关闭
using (FileStream fs = File.Create(f))
{
//建立字节组,并设置它的大小是多少字节
byte[] bytes = new byte[];
int n = ;
while (n > )
{
//一次从流中读多少字节,并把值赋给N,当读完后,N为0,并退出循环
n = stream.Read(bytes, , );
fs.Write(bytes, , n); //将指定字节的流信息写入文件流中
}
}
}
//return flag;
//return _outPath + saveLoadFile;
return f;
}
#endregion 从网站上下载文件,保存到其他路径
2.ftp模式的pdf文件
/// <summary>
/// 下载FTP文件。
/// </summary>
/// <param name="offsetPath">相对路径</param>
/// <param name="fileName">文件名称</param>
/// <returns>下载结果,本地文件路径</returns>
public string DownLoad(string offsetPath,string fileName)
{
try
{
FtpWebRequest ftpWeb = (FtpWebRequest)WebRequest.Create(_ftpRootPath + offsetPath + fileName);
ftpWeb.Method = WebRequestMethods.Ftp.DownloadFile;
ftpWeb.UseBinary = true;
var resp = ftpWeb.GetResponse();
using (FileStream fs = new FileStream(_outPath + fileName, FileMode.Create))
{
using (var s = resp.GetResponseStream())
{
if (s == null) { return "文件不存在!"; } int readCout = ;
byte[] bytes = new byte[];
readCout = s.Read(bytes, , );
while (readCout > )
{
fs.Write(bytes, , readCout);
readCout = s.Read(bytes, , );
}
}
}
resp.Close();
return _outPath + fileName;
}
catch (Exception e)
{
return e.Message;
} } /// <summary>
/// 判断文件是否存在
/// </summary>
/// <param name="offsetPath"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public bool FileExists(string offsetPath, string fileName)
{
try
{
FtpWebRequest ftpWeb = (FtpWebRequest)WebRequest.Create(_ftpRootPath + offsetPath + fileName);
ftpWeb.Method = WebRequestMethods.Ftp.DownloadFile;
ftpWeb.UseBinary = true;
var resp = (FtpWebResponse)ftpWeb.GetResponse();
resp.Close();
return true;
}
catch (Exception)
{
return false;
}
} /// <summary>
/// 获取目录下所有文件
/// </summary>
/// <returns></returns>
public string[] Files(string offsetPath)
{
try
{
FtpWebRequest ftpWeb = (FtpWebRequest)WebRequest.Create(_ftpRootPath + offsetPath);
ftpWeb.Method = WebRequestMethods.Ftp.ListDirectory;
Stream stream = ftpWeb.GetResponse().GetResponseStream();
if (stream == null)
{
return null;
}
List<string> fileList = new List<string>();
using (StreamReader sr = new StreamReader(stream))
{
StringBuilder sb = new StringBuilder();
do
{
sb.Append(sr.ReadLine());
if (sb.Length > )
{
fileList.Add(sb.ToString());
sb.Clear();
}
else
{
break;
}
} while (true);
}
return fileList.ToArray();
}
catch (Exception)
{
return null;
}
}
C# 导出pdf(浏览器不预览直接下载)的更多相关文章
- html+ashx + NPOI 实现导出Excel文件并且预览和下载
先看看实现效果 简单描述一下实现过程: 1. 生成报表,返回报表文件路径 $.post 请求一般处理文件ashx ,通过npoi生成对应的excel文件.生成成功后,返回文件保存的完整路径 2. ...
- PDF文件预览和下载
背景:项目中实现pdf文件的预览以及下载 环境:jdk1.8.SpringBoot2.0.Maven PDF.js下载地址将下载的源码拷入项目中 修改viewer.js: 将default ...
- 网页中动态嵌入PDF文件/在线预览PDF内容https://www.cnblogs.com/xgyy/p/6119459.html
#网页中动态嵌入PDF文件/在线预览PDF内容# 摘要:在web开发时我们有时会需要在线预览PDF内容,在线嵌入pdf文件: 问题1:如何网页中嵌入PDF: 在网页中: 常用的几种PDF预览代码片段如 ...
- Node.js + gulp 合并静态页模版,文件更新自动热重载。浏览器可预览
github地址:https://github.com/Liaozhenting/template 使用的是ejs的语法.其实你用什么文件后缀都可以,都是按ejs来解析. 模板文件放在componen ...
- 【ASP.NET 进阶】PDF文件在线预览(类似百度文库)
工作需要完成文档的在线预览,现在完成了第一步PDF文件的预览,步骤是通过PDF转换工具pdf2swf.exe把PDF文件转换为SWF文件,然后通过FlexPaper就可以预览了.效果如下(GIF图片太 ...
- VS Code 如何直接在浏览器中预览页面
VS Code 预览html页面的时候,默认需要在资源管理器中显示,再在浏览器中预览.今天介绍一下如何直接预览html页面. 方法一:自己配置快捷键 1.ctrl + shift + p 或者 F1 ...
- sublime text3 自己定义的不同浏览器的预览快捷键
sublime text3 自己定义的不同浏览器的预览快捷键突然全部失效了,搞到现在一直没闹清楚怎么回事,翻看插件发现SideBarEnhancements这插件刚更新了,快捷键也是依赖这个插件弄得. ...
- 使用java的 htpUrlConnection post请求 下载pdf文件,然后输出到页面进行预览和下载
使用java的 htpUrlConnection post请求 下载pdf文件,然后输出到页面进行预览和下载 2018年06月07日 10:42:26 守望dfdfdf 阅读数:235 标签: jav ...
- sublime text2-text3 定义的不同浏览器的预览快捷键
sublime text3 自己定义的不同浏览器的预览快捷键突然全部失效了,搞到现在一直没闹清楚怎么回事,翻看插件发现SideBarEnhancements这插件刚更新了,快捷键也是依赖这个插件弄得. ...
随机推荐
- 微擎签名出错 invalid signature
微擎签名出错 错误信息: config:fail,Error: 系统错误,错误码:63002,invalid signature 修改方法: PHP 端 $account_api = WeAccoun ...
- 【前端知识体系-CSS相关】Bootstrap相关知识
1.Bootstrap 的优缺点? 优点:CSS代码结构合理,现成的代码可以直接使用(响应式布局) 缺点:定制流程较为繁琐,体积大 2.如何实现响应式布局? 原理:通过media query设置不同分 ...
- Discovery and auto register
1.Discovery 2. auto register 2.1 agent 端配置 2.2 server 端配置
- 父组件向子组件传值时,值已经传过来却没有触发子组件的watch监听,解决~
需求: 父组件像封装的子组件传值 (父组件属性传值,子组件props接受) 子组件接受后经过处理回显页面; 预想:子组件接受值 , 经过watch监听,在监听中处理数据,回显数据; 问题:子组件 ...
- PL真有意思(六):子程序和控制抽象
前言 在之前我们把抽象定义为一种过程,程序员可以通过它将一个名字与一段可能很复杂的程序片段关联起来.抽象最大的意义就在于,我们可以从功能和用途的角度来考虑它,而不是实现. 在大多数程序设计语言中,子程 ...
- 高效PHP Redis缓存技术,可参考下步骤
是否想过PHP使用redis作为缓存时,如何能: 前后台模块共用Model层: 但是,不能每个Model类都进行缓存,这样太浪费Redis资源: 前后台模块可以自由决定从数据库还是从缓存读数据: 没有 ...
- 【Android - 组件】之Activity的启动模式
Activity的启动模式目前有四种:standard.singleTop.singleTask 和 singleInstance. 1.standard standard 是标准模式,也是系统的默认 ...
- 文件系统之LVM 逻辑卷管理
1. LVM介绍 LVM 是 Logical Volume Manager 的简称,中文就是逻辑卷管理. 物理卷(PV,Physical Volume):就是真正的物理硬盘或分区. 卷组(VG,Vol ...
- git的用法 回到某个版本
进入到项目文件夹 如果新建项目时没有勾选git 进入到项目中
- 华为云OCR文字识别 免费在线体验!
嘿,华为云OCR文字识别了解一下,免费在线体验! 物流行业快速提取运单信息.医疗/保险行业单据快速录入.政务办事人证检验,你知道这些都是如何实现的么? 答案就是:OCR文字识别! 作为AI时代效率倍增 ...