Rectangle 27 4

FPDF sends a PDF file, not HTML. So by default, the browser just prompts the person to download it, or if you have a plugin, it will open it in the browser. As far as using a title, the PDF viewer or PDF plugin will most likely use the file name or title of the document as the title of the page. ($pdf->SetTitle('FPDF tutorial');)

Again, FPDF outputs PDF not HTML. If you start output-ing HTML, then try to echo the PDF content, it will be jibberish. PHP will also not let you modify headers after output (HTML) has started, which throws an error.

If you stored the PDF on the system or were able to configure routes to the FPDF module, you could use HTML and the <object> tag to include it on a page, but that would be a different set up and would require a few more steps. By doing this, you could add all the HTML you wanted, and just show the PDF in a small screen on the page.

Unfortunately I've tried $pdf->SetTitle etc and in this instance it doesn't work, might look into the <object> tag option. Thanks Tim :)

php - How to get page title on fpdf output? - Stack Overflow

php title fpdf page-title
Rectangle 27 2

An .xls file is a binary format, not just a .csv file with a different delimiter. (Open one with a hex viewer to see the difference.) The .xls file format is documented in Microsoft Office Excel 97 - 2007 Binary File Format Specification (*.xls 97-2007 format) - note this is a download link to a .xps file, not an HTML page.

.xlsx

If you want Excel to open your file as a CSV file when you double-click it, give it a .csv extension and associate Excel with .csv files (if it isn't already).

How can we generate ans .xls file via php or asp?

@RNKushwaha: That has nothing to do with the question asked here. If you have a new question, first search this site to see if it's been answered before. If it has not, then post your own new question.

csv - What delimiter should I use instead of a , so that excel would r...

excel csv
Rectangle 27 1

The safest way to have a PDF display instead of download seems to be embedding it using an object or iframe element. There are also 3rd party solutions like Google's PDF viewer.

There's also DoPDF, a Java based In-browser PDF viewer. I can't speak to its quality but it looks interesting.

Show a PDF files in users browser via PHP/Perl - Stack Overflow

php perl pdf
Rectangle 27 1

You have to tell the browser what you are sending back so that the browser can take appropriate action like launching a PDF viewer if its a PDF that is being received or launching a video player to play video file ,rendering the HTML if the content type is simple html response, save the bytes of the response as a downloaded file, etc.

some common MIME types are text/html,application/pdf,video/quicktime,application/java,image/jpeg,application/jar etc

In your case since you are sending HTML response to client you will have to set the content type as text/html

In addition to telling the OP what they have to accomplish, you should actually explain how to do it (generally, this means with code.) Also, this post already has five answers, one of which is accepted, and is from four years ago. As such, I would recommend that you try to answer newer questions.

java - what is the use of "response.setContentType("text/html")" in se...

java servlets
Rectangle 27 1

You have to tell the browser what you are sending back so that the browser can take appropriate action like launching a PDF viewer if its a PDF that is being received or launching a video player to play video file ,rendering the HTML if the content type is simple html response, save the bytes of the response as a downloaded file, etc.

some common MIME types are text/html,application/pdf,video/quicktime,application/java,image/jpeg,application/jar etc

In your case since you are sending HTML response to client you will have to set the content type as text/html

In addition to telling the OP what they have to accomplish, you should actually explain how to do it (generally, this means with code.) Also, this post already has five answers, one of which is accepted, and is from four years ago. As such, I would recommend that you try to answer newer questions.

java - what is the use of "response.setContentType("text/html")" in se...

java servlets
Rectangle 27 0

FPDF sends a PDF file, not HTML. So by default, the browser just prompts the person to download it, or if you have a plugin, it will open it in the browser. As far as using a title, the PDF viewer or PDF plugin will most likely use the file name or title of the document as the title of the page. ($pdf->SetTitle('FPDF tutorial');)

Again, FPDF outputs PDF not HTML. If you start output-ing HTML, then try to echo the PDF content, it will be jibberish. PHP will also not let you modify headers after output (HTML) has started, which throws an error.

If you stored the PDF on the system or were able to configure routes to the FPDF module, you could use HTML and the <object> tag to include it on a page, but that would be a different set up and would require a few more steps. By doing this, you could add all the HTML you wanted, and just show the PDF in a small screen on the page.

Unfortunately I've tried $pdf->SetTitle etc and in this instance it doesn't work, might look into the <object> tag option. Thanks Tim :)

php - How to get page title on fpdf output? - Stack Overflow

php title fpdf page-title
Rectangle 27 0

My scenario is exactly that! I'm using chrome version 61.0.3163.100. I guess it's some browser flaw, but I did not find anything on google's forums. I am in doubt whether to download the file directly but would not want to give up the chrome PDF viewer.

Temporarily, I have found an ugly and inelegant solution until I have a definitive answer. I created a link in the generated window:

var newWindow = window.open("", "PDF", 'dependent=yes,locationbar=no,scrollbars=no,menubar=no,resizable,screenX=50,screenY=50,width=850,height=800');
newWindow.document.write(
'<html><body><center>' +
'<a title="Download File" style="font-family: \'Verdana\';color: #333;text-decoration: none;font-weight: 600;" download="File.PDF" href="data:application/pdf;base64,' + base64 + '">Download File</a>' +
'</center><br>' +
'<object width=100% height=100% type="application/pdf" data="data:application/pdf;base64,' + base64  + '">' +
'<embed type="application/pdf" src="data:application/pdf;base64,' + base64  + '" id="embed_pdf"></embed>' +
 '</object></body></html>');
 newWindow.window.focus();

javascript - Google Chrome - PDF Download in an iFrame not working - S...

javascript google-chrome pdf iframe downloading
Rectangle 27 0

Application feature control gives organisations full management of application features and functions with no complex changes to theapplication back-end. Tabs, menu options, buttons and links can be can be disabled or removed from view, or their use can simply be monitored and logged. Application feature control features for Google Apps include:

Gmail can be made corporate-only, File attach to Gmail messages can be removed, Chat boxes removed, Sharing options removed from menu or document editor in Google Drive

It would be better to include code/examples/an explanation here and provide the link as backup for more detailed information

html - Google Docs viewer disable download - Stack Overflow

html pdf iframe google-docs
Rectangle 27 0

Well finally I have got a way to do the task properly, see my fiddle if you want to look further at it. This script automatically do everything as required by my previous problem, and it forces pdf download without disabling the viewer.

(function(ElementTypeToDownload, DownloadFromWhere) {

  // from http://stackoverflow.com/questions/3077242/force-download-a-pdf-link-using-javascript-ajax-jquery and http://stackoverflow.com/questions/16611497/how-can-i-get-the-name-of-an-html-page-in-javascript
  // Anonymous "self-invoking" function
  if (!(typeof jQuery === 'function')) {
    (function() {
      var startingTime = new Date().getTime();
      // Load the script
      var script = document.createElement("SCRIPT");
      script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
      script.type = 'text/javascript';
      document.getElementsByTagName("head")[0].appendChild(script);

      // Poll for jQuery to come into existance
      var checkReady = function(callback) {
        if (window.jQuery) {
          callback(jQuery);
        } else {
          window.setTimeout(function() {
            checkReady(callback);
          }, 20);
        }
      };

      // Start polling...
      checkReady(function($) {
        $(function() {
          var endingTime = new Date().getTime();
          var tookTime = endingTime - startingTime;
        });
      });
    })();
  }
  // http://facebook.com/anders.tornblad
  // anders.tornblad@gmail.com

  // from http://stackoverflow.com/questions/3077242/force-download-a-pdf-link-using-javascript-ajax-jquery
  function SaveToDisk(fileURL, fileName) {
    // for non-IE
    if (!window.ActiveXObject) {
      var save = document.createElement('a');
      save.href = fileURL;
      save.target = '_blank';
      save.download = fileName || fileURL.split("/").pop() || 'unknown';

      var evt = new MouseEvent('click', {
        'view': window,
        'bubbles': true,
        'cancelable': false
      });
      save.dispatchEvent(evt);

      (window.URL || window.webkitURL).revokeObjectURL(save.href);
    }

    // for IE < 11
    else if (!!window.ActiveXObject && document.execCommand) {
      var _window = window.open(fileURL, '_blank');
      _window.document.close();
      _window.document.execCommand('SaveAs', true, fileName || fileURL)
      _window.close();
    }
  }

  // from http://stackoverflow.com/questions/4623982/test-if-jquery-is-loaded-not-using-the-document-ready-event
  function preInit() {
    // wait until jquery is loeaded
    if (!(typeof jQuery === 'function')) {
      window.setTimeout(function() {
        //console.log(count++);
        preInit();
      }, 10); // Try again every 10 ms..
      return;
    }

    $(ElementTypeToDownload || prompt("Enter the type of element you are going to download, e.g. 'a' for link, 'img' or 'image' for images (do not add quotes, deafult is 'a') ") || 'a', DownloadFromWhere || prompt("jQuery Selector for the place that you want to download content from, e.g. '#DivName', '.ClassName', 'TagName', body by deafult") || 'body').each(function() {
      var tag = (ElementTypeToDownload == 'img' || ElementTypeToDownload == 'image') ? 'src' : 'href';
      SaveToDisk($(this).attr(tag));
    });
  }

  preInit();
})();

If you already had worked it out, then why ask?

I asked because I found don't figure out how to achieve the result, but I found it when I have searched and combined multiple SO questions, so I made one on my own. Anyway big thanks for your help.

javascript - Downloading ALL pdf from links in a specific div/table el...

javascript html pdf download
Rectangle 27 0

Sometimes "low-tech" is the way to go. Can't you have your source viewer of you browser linked to something like PSPad. Then it's just a single click to tidy the HTML/XML and you have a nicely formatted xml doc to "enjoy". I know, I know, this means install and download things etc, but still...

I just replied to another post regarding using yahoo's YQL to query any page and return it as JSON, which can then be embedded directly into your html page as a <script> tag. You may have to do something like that to get this all to play nice. Not sure how helpful my answer was as I've never had to do this myself, but if you're curious:

Incidentally, why is it that nothing displays in the browser?

Re: Nothing displayed in the browser. Huh. I never thought about that. The server provides the data as 'text/html' even though it is XML. I suspect that is enough to cause Chrome and Firefox to ignore it.

The low-tech way is kind of intrusive to me and the other developers. I don't particular want to change to PSPad just for this.

javascript - Client side XSLT transformation of someone else's XML - S...

javascript xml
Rectangle 27 0

An .xls file is a binary format, not just a .csv file with a different delimiter. (Open one with a hex viewer to see the difference.) The .xls file format is documented in Microsoft Office Excel 97 - 2007 Binary File Format Specification (*.xls 97-2007 format) - note this is a download link to a .xps file, not an HTML page.

.xlsx

If you want Excel to open your file as a CSV file when you double-click it, give it a .csv extension and associate Excel with .csv files (if it isn't already).

How can we generate ans .xls file via php or asp?

@RNKushwaha: That has nothing to do with the question asked here. If you have a new question, first search this site to see if it's been answered before. If it has not, then post your own new question.

csv - What delimiter should I use instead of a , so that excel would r...

excel csv
Rectangle 27 0

/// <summary>
/// Convert the HTML code from the specified URL to a PDF document
    and send the document to the browser
/// </summary>
private void ConvertURLToPDF()
{
    string urlToConvert = textBoxWebPageURL.Text.Trim();

    // Create the PDF converter. Optionally the HTML viewer width can
        be specified as parameter
    // The default HTML viewer width is 1024 pixels.
    PdfConverter pdfConverter = new PdfConverter();

    // set the license key - required
    pdfConverter.LicenseKey = "R8nYyNnI2MjRxtjI29nG2drG0dHR0Q==";

    // set the converter options - optional
    pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
    pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal;
    pdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;


    // set if header and footer are shown in the PDF - optional - default
        is false 
    pdfConverter.PdfDocumentOptions.ShowHeader = cbAddHeader.Checked;
    pdfConverter.PdfDocumentOptions.ShowFooter = cbAddFooter.Checked;
    // set if the HTML content is resized if necessary to fit the PDF
        page width - default is true
    pdfConverter.PdfDocumentOptions.FitWidth = cbFitWidth.Checked;

    // set the embedded fonts option - optional - default is false
    pdfConverter.PdfDocumentOptions.EmbedFonts = cbEmbedFonts.Checked;
    // set the live HTTP links option - optional - default is true
    pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = cbLiveLinks.Checked;

    // set if the JavaScript is enabled during conversion to a PDF - default
        is true
    pdfConverter.JavaScriptEnabled = cbClientScripts.Checked;

    // set if the images in PDF are compressed with JPEG to reduce the
        PDF document size - default is true
    pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = cbJpegCompression.Checked;

    // enable auto-generated bookmarks for a specified list of HTML selectors
        (e.g. H1 and H2)
    if (cbBookmarks.Checked)
    {
        pdfConverter.PdfBookmarkOptions.HtmlElementSelectors = new string[] { "H1", "H2" };
    }

    // add HTML header
    if (cbAddHeader.Checked)
        AddHeader(pdfConverter);
    // add HTML footer
    if (cbAddFooter.Checked)
        AddFooter(pdfConverter);

    // Performs the conversion and get the pdf document bytes that can

    // be saved to a file or sent as a browser response
    byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(urlToConvert);

    // send the PDF document as a response to the browser for download
    System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
    response.Clear();
    response.AddHeader("Content-Type", "application/pdf");
    if (radioAttachment.Checked)
        response.AddHeader("Content-Disposition", 
                String.Format("attachment; filename=GettingStarted.pdf; size={0}", 
                pdfBytes.Length.ToString()));
    else
        response.AddHeader("Content-Disposition", 
                String.Format("inline; filename=GettingStarted.pdf; size={0}", 
                pdfBytes.Length.ToString()));
    response.BinaryWrite(pdfBytes);
    // Note: it is important to end the response, otherwise the ASP.NET
    // web page will render its content to PDF document stream
    response.End();
}

why are you giving me an example in C#?

ruby on rails - Generating pdf from html using Prawn - Stack Overflow

ruby-on-rails ruby pdf-generation prawn
Rectangle 27 0

You can host your PDF files on Google Docs and prevent viewer downloads. To do this do followings:

  • Once you login into your Google Docs account at docs.google.com website, you should see listing of documents in your account. Right click specific document that you want to secure by disabling download option.
  • Then click on prevent viewers from downloading option. This will remove downloading option and other users viewing the document cannot download the document file as a whole and reproduce its copy.

Also note, since you can only prevent downloading of documents created by you, click Owned by Me option on left side. This will display document created and owned by you. Then you can disable and prevent document downloading option for files on display.

Then you can just share this PDF on your website. IT will be view only. The code will look like that:

<iframe src="url to pdf/preview" width="640" height="480"></iframe>

html - Google Docs viewer disable download - Stack Overflow

html pdf iframe google-docs
Rectangle 27 0

You could put the docs into Google docs and embed the docs viewer into your site. Of course, there's no stopping people from taking screenshots, copy/pasting text, downloading HTML, etc.

php - how to make a user restrict to download? - Stack Overflow

php html
Rectangle 27 0

Here is a pdf viewer in javascript and html called pdf.js. However, in order for the pdf to get to the browser, it will still need to be downloaded.

There is no way to display something in a browser without downloading it. It may take a bit of work to find the original asset (looking through the network tab in chrome dev tools) but the original pdf will still be downloaded.

javascript - View PDF files on a Web page without downloading? - Stack...

javascript html5 pdf open-source
Rectangle 27 0

Rendering the pages on the server

It is not possible. At least not that simple. Some web browsers don't display PDFs but ask the user to download the file, some display them themselves, some embed an external PDF viewer component, some start an external PDF viewer. There is no standard, cross browser way to embed PDF into HTML, which would be needed if you want to display arbitrary text and the PDF content.

A fallback solution, working on every browser, would be rendering the PDF pages on the server as images and serve those to the client. This puts some stress on the server (processor, memory/disk for caching, bandwidth).

Some modern, HTML5 capable browsers can render PDFs with Mozilla's pdf.js on a canvas element.

<embed>
<object>

Rendering and serving the PDF pages as images needs some software on the server to query the number of pages and to extract and render a given page as image.

The number of pages can be determined with the pdfinfo program from Xpdf or the libpoppler command line utilities. Converting a page from the PDF file to a JPG image can be done with convert from the ImageMagick tools. A very simple CGI program using these programs:

#!/usr/bin/env python
import cgi
import cgitb; cgitb.enable()
import os
from itertools import imap
from subprocess import check_output

PDFINFO = '/usr/bin/pdfinfo'
CONVERT = '/usr/bin/convert'
DOC_ROOT = '/home/bj/Documents'

BASE_TEMPLATE = (
    'Content-type: text/html\n\n'
    '<html><head><title>{title}</title></head><body>{body}</body></html>'
)
PDF_PAGE_TEMPLATE = (
    '<h1>{filename}</h1>'
    '<p>{prev_link} {page}/{page_count} {next_link}</p>'
    '<p><img src="{image_url}" style="border: solid thin gray;"></p>'
)

SCRIPT_NAME = os.environ['SCRIPT_NAME']


def create_page_url(filename, page_number, type_):
    return '{0}?file={1}&page={2}&type={3}'.format(
        cgi.escape(SCRIPT_NAME, True),
        cgi.escape(filename, True),
        page_number,
        type_
    )


def create_page_link(text, filename, page_number):
    text = cgi.escape(text)
    if page_number is None:
        return '<span style="color: gray;">{0}</span>'.format(text)
    else:
        return '<a href="{0}">{1}</a>'.format(
            create_page_url(filename, page_number, 'html'), text
        )


def get_page_count(filename):

    def parse_line(line):
        key, _, value = line.partition(':')
        return key, value.strip()

    info = dict(
        imap(parse_line, check_output([PDFINFO, filename]).splitlines())
    )
    return int(info['Pages'])


def get_page(filename, page_index):
    return check_output(
        [
            CONVERT,
            '-density', '96',
            '{0}[{1}]'.format(filename, page_index),
            'jpg:-'
        ]
    )


def send_error(message):
    print BASE_TEMPLATE.format(
        title='Error', body='<h1>Error</h1>{0}'.format(message)
    )


def send_page_html(_pdf_path, filename, page_number, page_count):
    body = PDF_PAGE_TEMPLATE.format(
        filename=cgi.escape(filename),
        page=page_number,
        page_count=page_count,
        image_url=create_page_url(filename, page_number, 'jpg'),
        prev_link=create_page_link(
            '<<', filename, page_number - 1 if page_number > 1 else None
        ),
        next_link=create_page_link(
            '>>',
            filename,
            page_number + 1 if page_number < page_count else None
        )
    )
    print BASE_TEMPLATE.format(title='PDF', body=body)


def send_page_image(pdf_path, _filename, page_number, _page_count):
    image_data = get_page(pdf_path, page_number - 1)
    print 'Content-type: image/jpg'
    print 'Content-Length:', len(image_data)
    print
    print image_data


TYPE2SEND_FUNCTION = {
    'html': send_page_html,
    'jpg': send_page_image,
}


def main():
    form = cgi.FieldStorage()
    filename = form.getfirst('file')
    page_number = int(form.getfirst('page', 1))
    type_ = form.getfirst('type', 'html')

    pdf_path = os.path.abspath(os.path.join(DOC_ROOT, filename))
    if os.path.exists(pdf_path) and pdf_path.startswith(DOC_ROOT):
        page_count = get_page_count(pdf_path)
        page_number = min(max(1, page_number), page_count)
        TYPE2SEND_FUNCTION[type_](pdf_path, filename, page_number, page_count)
    else:
        send_error(
            '<p>PDF file <em>{0!r}</em> not found.</p>'.format(
                cgi.escape(filename)
            )
        )


main()

There is Python bindings for libpoppler, so the call to the external pdfinfo program could be replaced quite easily with that module. It may also be used to extract more information for the pages like links on the PDF pages to create HTML image maps for them. With the libcairo Python bindings installed it may be even possible to do the rendering of a page without an external process.

Can you suggest an alternative solution where this can be achieved?

@user956424 I've added a CGI that renders the pages on the server. Why no JavaScript? Why CGI (instead of WSGI)? Where do these requirements come from?

Given the other constraints this is not possible IMHO. You'll have to allow JavaScript and/or third party browser plugins and have to live with the fact not every browser will be able to display it the way you want. You may also pre-render and/or cache page images on the server to lower the CPU load with a solution that renders the pages on the server.

html - how to display pdf file contents as well as its full name in th...

python html cgi content-type
Rectangle 27 0

This technique will still allow the user to "make a copy" and with ownership this brings they can then download as they please. Not tested this, but I'm pretty sure I'm right...

what technique are you talking about?

html - Google Docs viewer disable download - Stack Overflow

html pdf iframe google-docs