java根据url生成pdf_如何从Java中的给定URL下载PDF?

Pshemo..

29

不要在这里使用读者和作者,因为它们旨在处理PDF不是的原始文本文件(因为它还包含许多其他信息,如有关字体,甚至图像的信息).而是使用Streams复制所有原始字节.

所以使用URL类打开连接.然后只需从其InputStream中读取并将原始字节写入您的文件.

(这是简化的示例,您仍然需要处理异常并确保在正确的位置关闭流)

System.out.println("opening connection");

URL url = new URL("https://upload.wikimedia.org/wikipedia/en/8/87/Example.JPG");

InputStream in = url.openStream();

FileOutputStream fos = new FileOutputStream(new File("yourFile.jpg"));

System.out.println("reading from resource and writing to file...");

int length = -1;

byte[] buffer = new byte[1024];// buffer for portion of data from connection

while ((length = in.read(buffer)) > -1) {

fos.write(buffer, 0, length);

}

fos.close();

in.close();

System.out.println("File downloaded");

从Java 7开始我们也可以使用

URL url = new URL("https://upload.wikimedia.org/wikipedia/en/8/87/Example.JPG");

try (InputStream in = url.openStream()) {

Files.copy(in, Paths.get("someFile.jpg"), StandardCopyOption.REPLACE_EXISTING);

} catch (IOException e) {

// handle exception

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java根据PDF模板生成PDF的过程可以通过使用JavaPDF库来实现。有一些流行的Java PDF库,如iText和Apache PDFBox,可以提供生成PDF的功能。这些库允许你使用Java代码来创建和编辑PDF文档,并且可以根据给定PDF模板生成新的PDF文件。 下面是一个使用iText库来根据PDF模板生成PDF的简单示例代码: ```java import com.itextpdf.text.Document; import com.itextpdf.text.pdf.PdfCopy; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; public class PdfGenerator { public static void main(String[] args) { try { // 读取PDF模板文件 PdfReader reader = new PdfReader("template.pdf"); // 创建新的PDF文件 Document document = new Document(); PdfCopy copy = new PdfCopy(document, new FileOutputStream("output.pdf")); document.open(); // 替换模板的内容 PdfStamper stamper = new PdfStamper(reader, copy); AcroFields form = stamper.getAcroFields(); form.setField("field1", "value1"); form.setField("field2", "value2"); stamper.close(); document.close(); System.out.println("PDF生成成功!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 这段代码首先使用PdfReader读取PDF模板文件,然后创建一个新的PDF文件。接着使用PdfStamper替换模板的内容,其`form.setField("field1", "value1")`语句用于替换PDF的字段内容。最后,通过关闭stamper和document来保存和关闭新生成PDF文件。 请注意,以上示例仅供参考,并且需要根据你的具体需求进行修改和适配。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值