openhtmltopdf icon indicating copy to clipboard operation
openhtmltopdf copied to clipboard

IllegalArgumentException for invalid URIs

Open appldev opened this issue 3 years ago • 0 comments

PDFRenderer.createPDF: If an image is embedded with an invalid URI (e.g. http:///static/images/footer/wikimedia-button.png) an uncaught IllegalArgumentException is thrown in com.openthmltopdf.swing.NaiveUserAgent$DefaultHttpStreamFactory#getUrl when conn.connect is called. The PDF creation is stopped

I tried using an own HttpStreamFactory and returning null in this case, but the calling method (NaiveUserAgent#openStream) is not nullsafe.

As a workaround, I made an own UriResolver (extending DefaultUriResolver), added the extractProtocol Method (which is normally called in openStream) and made an Override of resolveURI so that null is returned in this error case:


	@Override
	public String resolveURI(String baseUri, String uri) 
	{
		String resolvedUri= super.resolveURI(baseUri, uri);
		
		try
		{
			String protocol = extractProtocol(resolvedUri);
			
			if(resolvedUri != null && "http".equals(protocol))
			{
                               URLConnection conn = new URL(resolvedUri).openConnection();
                               conn.setConnectTimeout(10000);
                               conn.setReadTimeout(30000);
                               conn.connect();
			}
		}
		catch(IllegalArgumentException e)
		{
			resolvedUri= null;
		}
		
		return resolvedUri;
	}

appldev avatar Dec 08 '21 10:12 appldev