2024年小升初教材变更了,但是书店买不到新教材,看到网上有电子版教材,就写了个方法将教材图片来取下来并生成PDF文档,这样方便打印学习了。在此处记录一下方法。

第一步:使用jsoup工具类抓取网页中的图片并保存本地:

public static void main(String[] args) throws IOException {
//网上电子版教材地址
   URL url= new URL("教材网络地址");
        Document doc = Jsoup.parse(url,30000);
        Elements images = doc.select("img"); //查找网页中的图片
        String basePath = "E:\\maths\\"; //保存到本地的地址
        int i = 1;
        for(Element img : images) {
            FileOutputStream os = new FileOutputStream(new File(basePath + i + ".png"));
            String src = null;
            //查看网页源码,获取图片地址,src或data-src
            if(img.hasAttr("src")) {
                src = img.attr("src");
            }else{
                src = img.attr("data-src");
            }
            if(StringUtils.isBlank(src)) {
                continue;
            }
            try {
                //将图片保存至本地
                os.write(ImageUtils.getImage(src));
            }catch (Exception e){
                System.out.println("error::" + src);
            }finally {
                os.close();
            }
            i++;
        }
    }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.

可能有些无用的广告图片也一并抓取了下来,手动删除无用的图片;

第二步:使用itextpdf工具类生成PDF文档:

使用maven引入itextpdf的jar包:

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

将图片按照顺序生成PDF文档:

public static void main(String[] args) throws IOException {
   String bashPath = "E:\\maths\\"; //图片所在的文件夹
   String pdfFile = bashPath + "maths.pdf"; //生成的PDF文件地址

    try  {
    //设置文档纸张大小及边距
        Document document = new Document(PageSize.A4,35f,30f,30f,25f);
        PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
        document.open();
        //此处为了按照顺序加入PDF,使用了名称顺序获取图片
        for (int i=2;i<199;i++) {
            File file = new File(bashPath + i + ".png");
            if (!file.exists()) {
                System.err.println("File not found: " + file);
                continue;
            }
            Image img = Image.getInstance(file.getAbsolutePath());
            //将图片按照纸张大小进行缩放宽度
            float ratio = PageSize.A4.getWidth() / img.getWidth();
            img.scalePercent(ratio * 85); // scalePercent expects a percentage
				//将图片加入文档
            document.add(img);
        }
        document.close();
        //生成PDF结束
        System.out.println("PDF created successfully.");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.

简单的两步就可以将网络上的电子版教材下载生成PDF文档了,然后打印出来给孩子学习。完美!!!