“name” web pdf for better default save filename in Acrobat?

后端 未结 16 1723
难免孤独
难免孤独 2020-12-14 00:09

My app generates PDFs for user consumption. The \"Content-Disposition\" http header is set as mentioned here. This is set to \"inline; filename=foo.pdf\", which should be

16条回答
  •  攒了一身酷
    2020-12-14 00:52

    Like you, I tried and tried to get this to work. Finally I gave up on this idea, and just opted for a workaround.

    I'm using ASP.NET MVC Framework, so I modified my routes for that controller/action to make sure that the served up PDF file is the last part of the location portion of the URI (before the query string), and pass everything else in the query string.

    Eg:

    Old URI:

    http://server/app/report/showpdf?param1=foo¶m2=bar&filename=myreport.pdf

    New URI:

    http://server/app/report/showpdf/myreport.pdf?param1=foo¶m2=bar

    The resulting header looks exactly like what you've described (content-type is application/pdf, disposition is inline, filename is uselessly part of the header). Acrobat shows it in the browser window (no save as dialog) and the filename that is auto-populated if a user clicks the Acrobat Save button is the report filename.

    A few considerations:

    In order for the filenames to look decent, they shouldn't have any escaped characters (ie, no spaces, etc)... which is a bit limiting. My filenames are auto-generated in this case, and before had spaces in them, which were showing up as '%20's in the resulting save dialog filename. I just replaced the spaces with underscores, and that worked out.

    This is by no names the best solution, but it does work. It also means that you have to have the filename available to make it part of the original URI, which might mess with your program's workflow. If it's currently being generated or retrieved from a database during the server-side call that generates the PDF, you might need to move the code that generates the filename to javascript as part of a form submission or if it comes from a database make it a quick ajax call to get the filename when building the URL that results in the inlined PDF.

    If you're taking the filename from a user input on a form, then that should be validated not to contain escaped characters, which will annoy users.

    Hope that helps.

提交回复
热议问题