4
4
46kvolamak2021-07-09 09:40:47
React
46kvolamak, 2021-07-09 09:40:47

How to convert blob to pdf file?

Using the react-pdf library, I create a pdf document and I need to send this file to the server immediately after downloading,

<PDFDownloadLink document={<MyDoc />} fileName="somename.pdf">
        {({ blob, url, loading, error }) => {
        return (
          <>
            <div onClick = {() => sendPdf(blob)}>Скачать</div>          
          </>
        )
        }}
      </PDFDownloadLink>

Here I am passing the blob parameter of my pdf file to a function that collects a new pdf file from the blob and sends it to the server. Am I doing it right, for some reason the converted new Pdf file does not open.

const formData = new FormData()
    const data2 = new File([blob], "abb", {
      type: "application/pdf"
    })
    formData.append('File', data2)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nadim Zakirov, 2021-07-09
@46kvolamak

A little different, the new File constructor is absolutely NOT needed here.
Do this:

// Асинхронная функция для отправки переданного Blob на сервер:

async function sendPdf(blob) {

    // Создаем форму с файлом:
    var form_data = new FormData();
    form_data.append('file', blob, 'somename.pdf');

    // Отправляем форму на сервер (замените адрес обработчика на свой):
    var response = await (await fetch('https://yousite.ru/handler.php', {
        method: 'POST',
        body: form_data
    })).text();

    // Выводим ответ сервера в консоли:
    console.log('Ответ сервера: ' + response);
    
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question