根据url导出pdf文件

根据url 下载pdf


//下载pdf的方法
 @RequestMapping(value = "/saveDate")
    @ResponseBody
    public void saveDate(String url, HttpServletRequest request,HttpServletResponse response){
        try {
            //这里我获取当前时间 
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");//20180315104140
            String timeStamp = sdf.format(new Date();
            //根据
            URL url = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(30000);
            conn.setConnectTimeout(30000);
            conn.setDoOutput(true);
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            conn.setDoInput(true);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            InputStream in = conn.getInputStream();
          
        //根据时间设置文件名
        timeStamp=timeStamp+ ".pdf";
          //响应输出流,让用户自己选择保存路径 报文头 可以根据自己下载的文件格式去查询响应的报文头
        response.addHeader("Content-disposition",
                "attachment; filename=\""+timeStamp+"\"");
        response.setContentType("application/pdf");

		byte[] buffer = new byte[1024];
		int bytesRead = -1;
		while ((bytesRead = in.read(buffer)) != -1) {
			 response.getOutputStream().write(buffer, 0, bytesRead);
		}
        in.close();
    }catch (Exception e){
        e.printStackTrace();
    }finally {
		try {
			in.close();
		} catch (IOException ex) {
			logger.error(ex.getMessage(), ex);
		}
		try {
			out.close();
		} catch (IOException ex) {
			logger.error(ex.getMessage(), ex);
		}
	}

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
用C#实现生成PDF文档(附源码) 收藏 //write by wenhui.org using System; using System.IO; using System.Text; using System.Collections; namespace PDFGenerator { public class PDFGenerator { static float pageWidth = 594.0f; static float pageDepth = 828.0f; static float pageMargin = 30.0f; static float fontSize = 20.0f; static float leadSize = 10.0f; static StreamWriter pPDF=new StreamWriter("E:\myPDF.pdf"); static MemoryStream mPDF= new MemoryStream(); static void ConvertToByteAndAddtoStream(string strMsg) { Byte[] buffer=null; buffer=ASCIIEncoding.ASCII.GetBytes(strMsg); mPDF.Write(buffer,0,buffer.Length); buffer=null; } static string xRefFormatting(long xValue) { string strMsg =xValue.ToString(); int iLen=strMsg.Length; if (iLen<10) { StringBuilder s=new StringBuilder(); int i=10-iLen; s.Append('0',i); strMsg=s.ToString() + strMsg; } return strMsg; } static void Main(string[] args) { ArrayList xRefs=new ArrayList(); //Byte[] buffer=null; float yPos =0f; long streamStart=0; long streamEnd=0; long streamLen =0; string strPDFMessage=null; //PDF文档头信息 strPDFMessage="%PDF-1.1 "; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage="1 0 obj "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="<> "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="stream "; ConvertToByteAndAddtoStream(strPDFMessage); ////////PDF文档描述 streamStart=mPDF.Length; //字体 strPDFMessage="BT /F0 " + fontSize +" Tf "; ConvertToByteAndAddtoStream(strPDFMessage); //PDF文档实体高度 yPos = pageDepth - pageMargin; strPDFMessage=pageMargin + " " + yPos +" Td " ; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage= leadSize+" TL " ; ConvertToByteAndAddtoStream(strPDFMessage); //实体内容 strPDFMessage= "(http://www.wenhui.org)Tj " ; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage= "ET "; ConvertToByteAndAddtoStream(strPDFMessage); streamEnd=mPDF.Length; streamLen=streamEnd-streamStart; strPDFMessage= "endstream endobj "; ConvertToByteAndAddtoStream(strPDFMessage); //PDF文档的版本信息 xRefs.Add(mPDF.Length); strPDFMessage="2 0 obj "+ streamLen + " endobj "; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage="3 0 obj <> endobj "; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage="4 0 obj <</Type /Pages /Count 1 "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="/Kids[ 3 0 R ] "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="/Resources<</ProcSet[/PDF/Text]/Font<> >> "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="/MediaBox [ 0 0 "+ pageWidth + " " + pageDepth + " ] >> endobj "; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage="5 0 obj <> endobj "; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage="6 0 obj <> endobj "; ConvertToByteAndAddtoStream(strPDFMessage); streamStart=mPDF.Length; strPDFMessage="xref 0 7 0000000000 65535 f "; for(int i=0;i<xRefs.Count;i++) { strPDFMessage+=xRefFormatting((long) xRefs[i])+" 00000 n "; } ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="trailer <> "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="startxref " + streamStart+" %%EOF "; ConvertToByteAndAddtoStream(strPDFMessage); mPDF.WriteTo(pPDF.BaseStream); mPDF.Close(); pPDF.Close(); } } }
在Spring Boot中导出PDF文件可以使用第三方库,比如iText或Apache PDFBox。以下是使用iText进行PDF导出的示例代码: 首先,需要将iText库添加到项目的依赖中。在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13</version> </dependency> ``` 接下来,创建一个用于导出PDF的控制器,在该控制器中定义一个处理请求的方法。在方法中使用iText库来生成PDF文件。 ```java import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; @Controller public class PdfController { @GetMapping("/exportpdf") public void exportPdf(HttpServletResponse response) throws IOException, DocumentException { response.setContentType(MediaType.APPLICATION_PDF_VALUE); response.setHeader("Content-Disposition", "attachment; filename=example.pdf"); Document document = new Document(); OutputStream outputStream = response.getOutputStream(); PdfWriter.getInstance(document, outputStream); document.open(); document.add(new Paragraph("Hello, World!")); document.close(); outputStream.close(); } } ``` 在上述代码中,我们使用`@GetMapping`注解来处理GET请求,并指定了导出PDFURL为`/exportpdf`。在`exportPdf`方法中,我们首先设置响应的内容类型为PDF,然后设置响应头部的Content-Disposition,指定文件名为example.pdf。 接下来,创建一个`Document`实例,并使用`PdfWriter`将文档写入输出流中。在文档中添加内容,这里我们添加了一个简单的段落"Hello, World!"。最后关闭文档和输出流。 当访问`/exportpdf`URL时,将会下载一个名为example.pdfPDF文件,其中包含"Hello, World!"的内容。 这只是一个简单的示例,你可以根据实际需求来生成更复杂的PDF文件。希望对你有所帮助!
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值