首页 > 解决方案 > PDF“Itext 用户代理”缓存大小以及如何清除它

问题描述

我的代码使用“飞碟用户代理”库从 html 模板生成 PDF/PPT 文件。

现在的问题是,Itext 使用缓存系统通过缓存而不是调用外部 URL 来访问图像和其他资源。我想知道如何清除这个缓存,或者刷新需要多少时间。我不知道我在这里绝望和无能为力,因为由于缺乏良好的文档,我什至无法理解这个工具。

1-你能解释一下 . 的作用是什么吗ReplacedElementFactory

2-在调查图书馆时,我发现了方法:

    public ImageResource getImageResource(String uri) {
    ImageResource resource = null;
    uri = this.resolveURI(uri);
    resource = (ImageResource)this._imageCache.get(uri);
    if (resource == null) {
        InputStream is = this.resolveAndOpenStream(uri);
        if (is != null) {
            try {
                URL url = new URL(uri);
                if (url.getPath() != null && url.getPath().toLowerCase().endsWith(".pdf")) {
                    PdfReader reader = this._outputDevice.getReader(url);
                    PDFAsImage image = new PDFAsImage(url);
                    Rectangle rect = reader.getPageSizeWithRotation(1);
                    image.setInitialWidth(rect.getWidth() * this._outputDevice.getDotsPerPoint());
                    image.setInitialHeight(rect.getHeight() * this._outputDevice.getDotsPerPoint());
                    resource = new ImageResource(uri, image);
                } else {
                    Image image = Image.getInstance(this.readStream(is));
                    this.scaleToOutputResolution(image);
                    resource = new ImageResource(uri, new ITextFSImage(image));
                }

                this._imageCache.put(uri, resource);
            } catch (Exception var16) {
                XRLog.exception("Can't read image file; unexpected problem for URI '" + uri + "'", var16);
            } finally {
                try {
                    is.close();
                } catch (IOException var15) {
                    ;
                }

            }
        }
    }

包含这行代码resource = (ImageResource)this._imageCache.get(uri);

我假设这是它从缓存中获取图像的地方,而不是寻找更新版本的图片。

3- Itext 多久刷新一次它的缓存,首先它的大小是多少,我如何为其指定路径,它如何存储它?

谢谢您的帮助。

标签: javaitextflying-saucer

解决方案


摘要: OP 可能使用了底部编号的解决方案。(3):通过命令行参数/配置文件禁用缓存。

这段代码不是来自 iText,而是来自flysaucer本身,但是由于您只复制和粘贴一种方法,因此人们真的很难回答。

正如您在顶部看到的那样,缓存大小为32 private static final int IMAGE_CACHE_CAPACITY = 32;

您还可以在代码中看到,关键URI resource = (ImageResource) _imageCache.get(uriStr);_imageCache.put(uriStr, resource);

因此,如果您在远程位置上的图像发生更改但 URI 保持不变,您将获得旧图像。所以你有几个选择:

  1. 禁用缓存
  2. 添加失效机制。这可以基于时间。例如,您知道服务器上的图像每 6 小时更改一次,然后相应地设置失效时间
  3. 添加哈希以验证图像是否已更改...

更新:我仍然不完全清楚你想要什么?您想在不更改代码的情况下禁用缓存功能吗?

  1. 您可以在每次图像更改时更改图像 URI(例如添加一些随机数...)(从而使其唯一)。如果可以重复使用图像,这将具有优势,它会更快。
  2. 您可以尝试调用clearImageCache()which 将清除缓存或[shrinkImage][2]旧图像将被丢弃(如果超过 32 个)
  3. 或者您使用 FlyinSaucer配置禁用缓存(例如将其设置为 0)。您正在寻找的关键是xr.image.cache-capacity. 您可以使用配置文件 (local.xhtmlrenderer.conf) 或将其指定为参数java -Dxr.image.cache-capacity=0

推荐阅读