locked
Encode/decode PDF file to/from base64 RRS feed

  • Question

  • Hello everybody.

    I'm trying to encode PDF file to base64 coding, but when I try to decode it back, so the result is not the same as original file. I tried to do it by this article (and some other, but this was main), but this process changes non-printable characters. For example, the first line of original PDF file looks like this: (In this line below are normal dots instead of non-printable characters for cr lf, because I was not able to put it here with them)

    %PDF-1.4..%âaIÓ..31 0 obj..<<../Type/Annot/Border [0 0 0]/H/I/Subtype/Link/

    but these cr lf characters are not in my result file.

    By using second way:

    $A = Get-Content $OriginalPath -Encoding 'default'
    #Also tried with different encodings
    $B =[Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($A))
    $bytes = [System.Convert]::FromBase64String($B)
    [IO.File]::WriteAllBytes($ResultPath, $bytes)

    my result has dots between all characeters. (and these dots represent spaces)

    % P.D.F.-.1...4. .%.â.a.I.Ó. .3.1. .0. .o.b.j. .<.<. ./ .T.y.p.e./.A.n.n.o.t

    Does anybody know, how to solve this? I appreciate every advice.

    Thank you. Daniel.


    Tuesday, December 11, 2018 10:26 AM

Answers

  • Like this:

    $pdf = Get-Content dnoc_TEST.pdf -raw
    $bytes = [System.Text.Encoding]::ASCII.GetBytes($pdf)
    $base64 =[Convert]::ToBase64String($bytes)

    or like this:

    $pdf = Get-Content dnoc_TEST.pdf -Encoding Byte
    $base64 =[Convert]::ToBase64String($pdf)


    \_(ツ)_/


    • Edited by jrv Tuesday, December 11, 2018 10:49 AM
    • Marked as answer by SYSKO company Tuesday, December 11, 2018 11:04 AM
    Tuesday, December 11, 2018 10:46 AM

All replies

  • Like this:

    $pdf = Get-Content dnoc_TEST.pdf -raw
    $bytes = [System.Text.Encoding]::ASCII.GetBytes($pdf)
    $base64 =[Convert]::ToBase64String($bytes)

    or like this:

    $pdf = Get-Content dnoc_TEST.pdf -Encoding Byte
    $base64 =[Convert]::ToBase64String($pdf)


    \_(ツ)_/


    • Edited by jrv Tuesday, December 11, 2018 10:49 AM
    • Marked as answer by SYSKO company Tuesday, December 11, 2018 11:04 AM
    Tuesday, December 11, 2018 10:46 AM
  • Thank you very much. The second way is exactly what I was looking for.

    Tuesday, December 11, 2018 11:00 AM
  • $bytes = [Convert]::FromBase64String($base64)
    [system.io.file]::WriteAllBytes('test.pdf',$bytes)


    \_(ツ)_/

    Tuesday, December 11, 2018 11:05 AM