PDF 'Itext User Agent' 缓存大小以及如何清除它

PDF 'Itext User Agent' cache size and how to clear it

我的代码使用 "Flying saucer User Agent" 库从 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 多久刷新一次它的缓存,首先它的大小是多少,我如何指定它的路径,它如何存储它?

感谢您的帮助。

Summary: The solution the OP probably used the one at the bottom no. (3): Disabling the cache via commandline parameter/config file.

此代码并非来自 iText,而是来自 flyingsaucer 本身,但由于您只复制并粘贴了一种方法,因此人们很难回答。

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

正如您在代码中看到的,keyURI resource = (ImageResource) _imageCache.get(uriStr);_imageCache.put(uriStr, resource);

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

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

更新:我还是不太清楚你想要什么?是否要在不更改代码的情况下禁用缓存功能?

  1. 您可以在每次图像更改时更改图像 URI(例如添加一些随机数...)(从而使其唯一)。如果图像可以重复使用,这样做的好处是速度会更快。
  2. 您可以尝试调用 clearImageCache() 这将清除缓存或 [shrinkImage][2] 并且旧图像将被删除(如果超过 32 个)
  3. 或者您使用 FlyinSaucer Configuration 禁用缓存(例如将其设置为 0)。您要查找的密钥是 xr.image.cache-capacity。您可以使用配置文件 (local.xhtmlrenderer.conf) 或将其指定为参数 java -Dxr.image.cache-capacity=0.