Open an existing pdf in webhtmlviewer

I have the native path to a pdf file and I want to display that pdf file in an webhtmlviewer or grafitti suite pdf viewer. Does anyone have some sample code to do that?
xojo 2024r2.1 on Win11
Thanks

Hi Gary,
The GraffitiSuite demo project includes an example of loading data using a WebFile’s Data property (pgePDFViewer.documentOpenButton.Pressed). The approach is similar except you’d use the constructor of WebFile to load the PDF file. Something like:

file = new WebFile(pdfFolderItem)
viewerDemo.OpenDocument(file)

If you wish to use a WebHTMLViewer, the approach is similar except you’d call the WebHTMLViewer.LoadURL method and pass the URL as the paramter:

file = new WebFile(pdfFolderItem)
HTMLViewer1.LoadURL(file.URL)

It’s important to remember that your WebFile must remain in-scope, so file would probably be a property on the view (WebPage or WebContainer):

Private Property file As WebFile
1 Like

Thanks Anthony. How do I prevent the pdf from automatically downloading.
It is displayed in the viewer but I don’t want it to automatically download.
Here is my code.

var pdffile as FolderItem
pdffile = New FolderItem(session.docloc)
file = New webfile(true)
PdfPreview1.OpenDocument(file.Open(pdffile, true))

I also tried file.forcedownload = False but is still downloads the file.

That’s odd. It appears that accessing the URL property of the WebFile is causing it regardless of the ForceDownload property’s value. Passing either to an HTMLViewer’s LoadURL method or a GraffitiPDFViewer’s OpenDocument method. I don’t remember that happening in the past. Surely overlooking something obvious…

I don’t see what’s causing it, and it’s easier for me to just bypass WebFile with GraffitiWebFile. Add this method to a module:

Public Sub LoadFolderItem(extends viewer as GraffitiPDFViewer, f as FolderItem)
  if f = nil or f.Exists = False then Return
  
  var data as String
  try
    var bs as BinaryStream = BinaryStream.Open( f )
    if bs <> nil then data = bs.Read( bs.Length )
  catch e as IOException
    Return
  end try
  
  if data.IsEmpty = False then
    var wf as new GraffitiWebFile( f.Name, "application/pdf", data.Bytes, data )
    viewer.OpenDocument( wf )
  end if
End Sub

Then you can call it like this:

var f as FolderItem = SpecialFolder.Desktop.Child( "pdf-sample.pdf" )
viewerDemo.LoadFolderItem( f )

Thanks Anthony
I did figure out how to use WebFile without downloading.

var f as FolderItem
f = New FolderItem(session.docloc)

if f = nil or f.Exists = False then Return

var data as String
try
var bs as BinaryStream = BinaryStream.Open( f )
if bs <> nil then data = bs.Read( bs.Length )
catch e as IOException
Return
end try

if data.IsEmpty = False then

session.file = New WebFile

session.file.Data = data

session.file.MIMEType = “application/pdf”

session.file.Filename = f.Name

session.file.ForceDownload = False

pdfpreview1.OpenDocument(session.file)
end if